Showing posts with label sed. Show all posts
Showing posts with label sed. Show all posts

Thursday, November 1, 2012

Using & as replacement for matched string in sed

This is useful, if you need to add some modification to your searched string in sed, but you are using regex and you do not know what the output would be. Please see below example:

$ echo "123 123 abc abc" | sed 's/[0-9]*/(&)/'
(123) 123 abc abc

In this example, your requirement is to put parentheses around your matched/searched string. So I put '&' as the replacement for the searched string, which is any series of number between 0 to 9, and put parentheses around it.

Done :)


Thursday, September 29, 2011

Replacing space with newline

There are a few ways to achieve that:

1. sed

$ echo "one two three" | sed 's/ /\n/g'
one
two
three
2. awk
$ echo "one two three" | awk '$1=$1' RS= OFS="\n"
one
two
three
3. tr
$ echo "one two three" | tr -s ' ' '\n'
one
two
three
3 ways to do it, have fun

Tuesday, September 27, 2011

Multiple sed expression in one line

To do multiple sed expression in one line, you can use -e a few times according to your need. For example:

To subtitute 'little' with 'big' and 'lamb' with 'cow' in "Mary had a little lamb" we can use:

$ echo 'Mary had a little lamb' | sed -e 's/little/big/' -e 's/lamb/cow/'
Mary had a big cow
where -e is for expression flag, 's/little/big/' is the first expression and 's/lamb/cow/' is the second expression

That's all.