Using mirrors in SED
September 4, 2011 Leave a comment
It took me long to discover mirrors in SED. That’s a feature that may help you a lot in some replacing problems. Mirrors are denoted by \1, \2, \3, .. \9 and are used to cut a part of the input string to use it in the replacement string, like a temporary variable. For use mirrors in SED, you need to use extended regexp, flag -r. Let’s see some applications:
Chaging a data:
$ echo 12/31/2004 | sed -r 's@([0-9][0-9])/([0-9]{2})/([0-9]{4})@\1.\2.\3@'
$ echo 12/31/2004 | sed -r 's@([0-9][0-9])/([0-9]{2})/([0-9]{4})@\2.\1.\3@'
$ echo 12/31/2004 | sed -r 's@([0-9][0-9])/([0-9]{2})/([0-9]{4})@\2-\1-\3@'
Inverting field order:
$ echo abcdefg | sed -r 's/(a)(b)(c)/\3:\2:\1/' $ echo abcdefg | sed -r 's/(a)(b)(c).*/\1:\2:\3/' $ echo abcdefg | sed -r 's/(a)(b)(c).*/\3:\2:\1/'
Read more:
http://aurelio.net/curso/sucesu/sucesu-seder-prompt.html
See ya!
Recent comments