Contact me sending an e-mail (antispam defense activated) |
Title: Do something with every char in a string Author: Sandro Tosi Last modified: 2006-05-17 The original need was to take a string as input and put every characters on a different line. And I think ``sed'' could be the right tool to do that. Thanks to ``TheBonsai'' on #sed IRC channel at freenode.net, this is the solution: $ echo -n "test" | sed 's/./&\n/g' (``echo -n'' doesn't print a newline char at the end of the printed string). The tip here is that ``&'' gets replaced by ``whatever matched''; note ``g'' at the end of the command: it means ``global'', otherwise only the first match is used. The first version was: $ echo -n "test" | sed 's/\(.\)/\1\n/g' less elegant than the previous one, since no grouping is needed for this task. Keep in mind that this will work only on GNU sed (and some other variants) since standard sed doesn't allow ``\n'' on substitution side, only as match. So, if you want to use this one-liner on a Solaris or AIX server, you have to do this way: $ echo -n "test" | sed 's/./& /g' yes, there is a RETURN between ``&'' and ``/''. |