Tuesday 6 August 2019

Linux :: grep nth line

Is there a nice unix tool to grep the nth line of a file?

Answers:



you can use sed
Code:
sed -n '45p' file

Good old-fashioned awk is incredibly useful for these small jobs:

awk '{ if (NR==45) print $0 }' file

Or, you can pass in n as a parameter if you want to make a script:

#!/bin/bash
# Usage getn N filename

awk '{ if(NR==n) print $0 }' n=$1 $2

the syntax is a bit cryptic, but easy to learn. $0 is the whole line. $1 would be the first
column, $2 the 2nd etc.


I just want to "extract" the n'th line of a file.
This will give me the 45'th line but with some additional info.

head -n44 file > tmp1.file
head -n45 file > tmp2.file
diff tmp1.file tmp2.file > difference


To grep the 45th line of file foo.txt for "hello"
$ head -45 foo.txt | tail -1 | grep hello

0 comments:

Post a Comment