Get specific line from text file using just shell script
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). I need to do this only using a basic shell script.
cat file | while read line
do
#do something
done
I know how to iterate through lines, as shown above, but what if I just need to get the contents of a particular line
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
.