Home Page

Tips page
c
cellulari
debian
egittologia
emacs
emacs-latex
hardware
html
inglese
java
latex
linux
matlab
misc
mysql
network
octave
programming
python
security
sed

*Do something with every char in a string

tech
webapps
windows

University Page

Programming

Debian & Linux

Some works

About me

Del.icio.us Bookmarks

BOINC Combined Statistics

Site Statistics

Contact me sending an e-mail (antispam defense activated)

debian

hacker emblem

blogger

GeoURL

View Sandro Tosi's profile on LinkedIn

This is my Google PageRank

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 ``/''.