Useful tips on sed and awk

I was recently developing a code where I came across various search techniques and pattern matching that is possible using ‘sed’ and ‘awk’. Am sharing some of those tips here :

  • You want to search and print the second category in a given file. Here is how a file looks like :

Apple

o

n

e

Apple

t

w

o

Apple

t

h

r

e

e

Command: sed -nr ‘/^Apple/H;//,/^done/G;s/\n(\n[^\n]*){2}$//p’  file_name

Output:

t

w

o

  • Printing the sum of a given column in a file :

1  1

2  4

3  9

Command: awk ‘{ sum += $2 } END { print sum }’  file_name

Output: 14

  • sed  has the N command which will read the next line into the pattern space.

Command:  sed -n ‘/pattern/{N;p}’ file_name

In order to print 2 lines simply put {N;N;p}

  • Print section of file based on line numbers (lines 2-10, inclusive)

Command: sed -n ‘2,10p’ file_name

  • Print the last line of a file (emulates “tail -1”) 

Command: sed -n ‘$p’ file_name

I came across this page to understand few one-liner commands.

%d bloggers like this: