Tuesday, September 22, 2009

Replace asterisk using sed - bash


For example:

$ countries="**India **South Africa **Sri Lanka **West Indies"
$ echo $countries
**India **South Africa **Sri Lanka **West Indies

Output required:
Replace "**" with a newline, so that above line becomes:

**India
**South Africa
**Sri Lanka
**West Indies

The sed replacement:

$ echo $countries | sed 's! **!\n**!g'
sed: -e expression #1, char 12: Invalid preceding regular expression

So you would need to escape the asterisk above.
i.e.

$ echo $countries | sed 's! \*\*!\n**!g'

Another way using sed:

$ echo $countries | sed 's! \*\*!\
\*\*!g'

Similarly:

$ echo "a,b,c,d" | sed 's!,!\n!g'

Output:
a
b
c
d

Related post:

1)
Suppose your i/p line is:

1 b 3 4 e 6 g 8 i j k

And you wish to split the above line into multiple lines (each line with say 3 entries)

i.e.

1 b 3
4 e 6
g 8 i
j k

here is a post

2)
One more related post of breaking a line into multiple lines based on length

No comments:

© Jadu Saikia www.UNIXCL.com