Skip to content
 

Reverse lines in sed

You may have seen the solution proposed by the SED oneliners:

# reverse each character on the line (emulates "rev")
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

Well, here is another (clearer?) way. It just uses a \n as a marker to separate the part of word that has been reversed so far from the part that hasn't. Finally, the \n is removed.

sed 's/^/\n/;:a; s/^\([^\n]*\n\)\(.\)/\2\1/;/\n$/!ba;s/\n//'
# Or, if your sed doesn't support [^\n], possibly less efficient:
sed 's/^/\n/;:a; s/^\(.*\n\)\(.\)/\2\1/;/\n$/!ba;s/\n//'