Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific line from text file using just shell script

Tags:

linux

shell

unix

sh

People also ask

How do I grep a specific line from a file?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


sed:

sed '5!d' file

awk:

awk 'NR==5' file

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

You could use sed -n 5p file.

You can also get a range, e.g., sed -n 5,10p file.


Best performance method

sed '5q;d' file

Because sed stops reading any lines after the 5th one

Update experiment from Mr. Roger Dueck

I installed wcanadian-insane (6.6MB) and compared sed -n 1p /usr/share/dict/words and sed '1q;d' /usr/share/dict/words using the time command; the first took 0.043s, the second only 0.002s, so using 'q' is definitely a performance improvement!


If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:

head -n 20 york.txt | tail -11

or

sed -n '10,20p' york.txt 

p in above command stands for printing.

Here's what you'll see: enter image description here