Reputation: 53
I have a text file in which every line has this format (the number of words before and after the comma may vary, but it is at least one before and one after it):
some words,a few other words
And I want its content to be displayed on the terminal like this:
a few other words some words
How can I do this? The only thing I can think of is using the tr
command to replace the comma with a space, but I have no clue as to how to change the order of the words.
Any help would be appreciated.
Upvotes: 1
Views: 462
Reputation: 6185
This is what AWK is for (when defining field separator to be the comma):
$ echo "some words,a few other words" | awk -F, '{ print $2,$1 }'
a few other words some words
Edit:
Just noticed that @fredtantini had the same (accepted) solution. I leave it here as it shows the solution in a more concise (clear) way (i.e., it doesn't utilise an external file).
Upvotes: 0
Reputation: 16556
If you don't mind using awk, you could use the -F
option:
$>cat f
some words,a few other words
foo,bar
$>awk -F',' '{print $2,$1}' f
a few other words some words
bar foo
An other option is using sed:
$>sed 's/\(.*\),\(.*\)/\2 \1/g' f
a few other words some words
bar foo
Finally, with a while loop:
$>while IFS=, read part1 part2; do echo "$part2" "$part1";done <f
a few other words some words
bar foo
You have to be sure that there is only 1 comma on each line though…
Upvotes: 1