View Full Version : grep nth line
monkeyking
March 22nd, 2007, 10:51 AM
Is there a nice unix tool to grep the nth line of a file?
thanks in advance
thumper
March 22nd, 2007, 10:55 AM
There are these wonderful inventions called pipes.
To grep the 45th line of file foo.txt for "hello"
$ head -45 foo.txt | tail -1 | grep hello
monkeyking
March 22nd, 2007, 11:03 AM
okay,
I wasn't clear enought,
I just want to "extract" the n'th line of a file.
I know I can do stuff like
head -n44 file > tmp1.file
head -n45 file > tmp2.file
diff tmp1.file tmp2.file > difference
This will give me the 45'th line but with some additional info.
xadder
March 22nd, 2007, 11:31 AM
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.
ghostdog74
March 22nd, 2007, 02:42 PM
you can use sed
sed -n '45p' file
in awk
awk 'NR==45' file
Mojtaba-Ebrahimi
August 21st, 2010, 10:01 PM
I have same problem priorly. there are many solution when your line number is a constant number. but if your line number saved in a variable use this one.
suppose your file name saved in a variable named File_Name and your favourite Line number saved in Line variable, then use this command:
cat -n $File_Name | grep " $Line"
now you can use cut command to cut additional information added by cat command:
cat -n $File_Name | grep " $Line" | cut -d: -f2
DaithiF
August 22nd, 2010, 02:15 PM
or just:
sed -n "${Line}p"
geirha
August 22nd, 2010, 03:25 PM
Bookmark this page http://mywiki.wooledge.org/BashFAQ, it answers alot of questions like this. For this question, number 11.
ghostdog74
August 23rd, 2010, 02:08 AM
or just:
sed -n "${Line}p"
sed -n "${Line}{p;q}"
Chasalin
January 25th, 2011, 04:59 PM
... and what if you're grepping from a file with numeric values, you want to get line numer 7, but '7' also appears in another line? (including the leading spaces...)
I think sed or awk is the way to go and head/tail is a nice trick.
suppose your file name saved in a variable named File_Name and your favourite Line number saved in Line variable, then use this command:
cat -n $File_Name | grep " $Line"
now you can use cut command to cut additional information added by cat command:
cat -n $File_Name | grep " $Line" | cut -d: -f2
slavik
January 26th, 2011, 02:56 AM
and this is an old thread and all solutions are available via google.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.