LinuxHelps.com

A blog for Linux Lovers.

Posted by sibu on December 28, 2011

SED and AWK command

sed (stream editor)

Sed is a non-interactive editor. Instead of altering a file by moving the cursor on the screen, you use a script of editing instructions to sed, plus the name of the file to edit. You can also describe sed as a filter.
Let’s have a look at some examples:
$sed ’s/to_be_replaced/replaced/g’ /tmp/dummy

Sed replaces the string ‘to_be_replaced’ with the string ‘replaced’ and reads from the /tmp/dummy file. The result will be sent to stdout (normally the console) but you can also add ‘> capture’ to the end of the line above so that sed sends the output to the file ‘capture’.
$sed 12, 18d /tmp/dummy

Sed shows all lines except lines 12 to 18. The original file is not altered by this command.

awk (manipulation of datafiles, text retrieval and processing)

Many implementations of the AWK programming language exist. AWK scans for a pattern, and for every matching pattern a action will be performed.

I’ve created a dummy file containing the following lines:
“test123
test
tteesstt”

$awk ‘/test/ {print}’ /tmp/dummy

test123
test

The pattern AWK looks for is ‘test’ and the action it performs when it found a line in the file /tmp/dummy with the string ‘test’ is ‘print’.
$awk ‘/test/ {i=i+1} END {print i}’ /tmp/dummy

Another example

-bash-3.00# ls -al |grep boot
-rw——- 1 root root 170 Aug 7 17:14 boot.log
-rw——- 1 root root 0 May 9 2010 boot.log.1
-rw——- 1 root root 0 May 2 2010 boot.log.2

-bash-3.00# ls -al |grep boot |awk ‘{print $9 }’
boot.log
boot.log.1
boot.log.2
-bash-3.00#

Add A Comment