I am trying to get a specific line from a text file.
So far, online I have only seen stuff like sed, (I can only use the sh -not bash or sed or anything like that).
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:
In parallel with William Pursell's answer, here is a simple construct which should work even in the original v7 Bourne shell (and thus also places where Bash is not available).
i=0
while read line; do
i=`expr "$i" + 1`
case $i in 5) echo "$line"; break;; esac
done <file
Notice also the optimization to break
out of the loop when we have obtained the line we were looking for.
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!
sed:
sed '5!d' file
awk:
awk 'NR==5' file
line=5; prep=`grep -ne ^ file.txt | grep -e ^$line:`; echo "${prep#$line:}"
You could use sed -n 5p file
.
You can also get a range, e.g., sed -n 5,10p file
.