Consider the following file called swap.txt:
349 230 481 800 456 129 043 942 584 901 627 874
Each three-digit number is separated by a space. Write a one-line sed command that performs in-place substitution to swap the first digit with the third digit of the first number in every line. For example, after running the appropriate sed command, the swap.txt file would contain:
943 230 481 008 456 129 340 942 584 109 627 874
For a bonus, can you swap the first digit with the third digit of the second number in every line? Do not worry about performing in-place substitution for this part. For example, after running the appropriate sed command, the following would be output to the terminal:
349 032 481 800 654 129 043 249 584 901 726 874
s
command will be used for substitution. Also, I will use parenthesis to define substring components that will help me in extracting number at a particular position. A character class([]
) is used to specify the numbers. Parenthesis must be escaped in sed command.
$sed 's/([0-9])([0-9])([0-9])/\3\2\1/' swap.txt
2
will be used as a flag to s
command because in the second part it is mentioned to do the same operation with the second number.
$sed 's/([0-9])([0-9])([0-9])/\3\2\1/2' swap.txt