SED tricks and hacks part 1

regular expression

Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). in this post I will show you how easy we can replace text, marge two line into one and strip multiple spaces to one.

1. Text replacing.

fist example will show us how easy we can replace text by sed. Just remmeber following syntax sed ‘s/what I want to change/what to be changed/’ .

# cat test.txt
This is UNIX.
We love UNIX.
We use UNIX.
#
# cat test.txt | sed 's/UNIX/Linux/'
This is Linux.
We love Linux.
We use Linux.
#

2. Merge two line to one.

sometimes we have relevant infomration devided between two line, but we need it in one linefor better reading. We can use sed command for this as follow.

# cat test.txt
Andrez Mercado
23
Leonor Gonzalez Mina
53
Ericson Alexander Molano
54
Jorge Onate
34
Elkin Ramirez
64
#
# cat test.txt | sed 'N;s/\n/ /'
Andrez Mercado  23
Leonor Gonzalez Mina  53
Ericson Alexander Molano  54
Jorge Onate  34
Elkin Ramirez  64
#

3. Strip multipe spaces to one.

In case we need to strip multiple spaces to one it’s very easy to use sed.

# cat test.txt
Andrez         Mercado
Leonor     Gonzalez               Mina
Ericson          Alexander      Molano
Jorge       Onate
Elkin            Ramirez
#
# cat test.txt | sed -e's/  */ /g'
Andrez Mercado
Leonor Gonzalez Mina
Ericson Alexander Molano
Jorge Onate
Elkin Ramirez
#

Leave a Reply