Reverse words with sed

Hi guys,

I'm wondering what the best way would be to reverse words in a string based on certain characters.

For example:

echo Word1Word2Word3Word4 | sed '
       /\n/ !G
       s/\(Word.\)\(.*\n\)/&\2\1/
       //D
     '

This returns:

Word4Word3Word2Word1

I'm no sed expert but this is what I made and does the job, I just wonder if there's an other/better way to achieve the same

This is fine - the only issue might be for maintenance, someone unfamiliar with sed would have issues learning what the code really does.

In the case where you need to reverse the words in a sentence, awk might be clearer--
ex:

echo 'This is a sentence'  | awk '{for(k=NF; k; k--) {printf("%s ", $(k)) }; print ""}'

The fact is you can do most text manipulations several ways in UNIX. And someone could make this awk more concise - but harder to interpret.

Linux (GNU coreutils) has special commands for text "reversal": tac and rev come to mind.

PS: your definition of reversal in your example is not what some developers probably have, and the same goes for "words" which are normally white space delimited, e.g., English.

1 Like

Thanks Jim, although it's not exactly what I was looking for.

I know the awk, tac and rev solutions but was especially interested in getting a good sed example for educational purposes as it was harder to create than I thought it would be.
Also note that there is no delimiter between the words in the string.