manpagez: man pages & more
info sed
Home | html | info | man

File: sed.info,  Node: Reverse chars of lines,  Next: Text search across multiple lines,  Prev: Print bash environment,  Up: Examples

7.6 Reverse Characters of Lines
===============================

This script can be used to reverse the position of characters in lines.
The technique moves two characters at a time, hence it is faster than
more intuitive implementations.

   Note the ‘tx’ command before the definition of the label.  This is
often needed to reset the flag that is tested by the ‘t’ command.

   Imaginative readers will find uses for this script.  An example is
reversing the output of ‘banner’.(1)

     #!/usr/bin/sed -f

     /../! b

     # Reverse a line.  Begin embedding the line between two newlines
     s/^.*$/\
     &\
     /

     # Move first character at the end.  The regexp matches until
     # there are zero or one characters between the markers
     tx
     :x
     s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
     tx

     # Remove the newline markers
     s/\n//g

   ---------- Footnotes ----------

   (1) This requires another script to pad the output of banner; for
example

     #! /bin/sh

     banner -w $1 $2 $3 $4 |
       sed -e :a -e '/^.\{0,'$1'\}$/ { s/$/ /; ba; }' |
       ~/sedscripts/reverseline.sed

© manpagez.com 2000-2026
Individual documents may contain additional copyright information.