AWK tricks and hacks Part 2

regular expression

In second part of AWK tricks and hacks will be described how to print lines between two patterns, how to add character, word or anything else on beginning and at the end of line.

Print lines between two patterns.

Very useful is to know how to print all lines between two patters. Using AWK we can do it easily like this.

 awk '/StartPattern/,/EndPattern/' FileName

And output is here:

# cat list.txt
Some LINUX
fedora
ubuntu
SuSE
RedHat
Some LINUX end
Some UNIX
HP-UX
AIX
Solaris
Some UNIX end
#
# cat list.txt | awk '/LINUX start/,/LINUX end/'
Some LINUX start
fedora
ubuntu
SuSE
RedHat
Some LINUX end
#

Add characters at the beginning of each line.

 awk '{print "add_to_beginning"$0}' file

With example.

# cat list.txt
fedora
ubuntu
SuSE
RedHat
#
# cat list.txt | awk '{print "LINUX "$0}'
LINUX fedora
LINUX ubuntu
LINUX SuSE
LINUX RedHat
#

Add characters at the end of each line.

 awk '{print $0"append_to_end"}' file

Example.

# cat list.txt | awk '{print $0" LINUX"}'
fedora LINUX
ubuntu LINUX
SuSE LINUX
RedHat LINUX
#

AWK tricks and hacks Part 1

Leave a Reply