Bash/sh: Reading a Specific Line from a Text File (by Line Number)

Practice



Task: read a specific line from a text file without needing to iterate through the whole file in the script.

For this, we use the out-of-the-box utility sed:

$ sed -n '20p' myfile.txt

in this example we read the line numbered 20 from the file. Lines are numbered starting from 1.

And here's a piece of a script where the variable MYVAR is assigned the line numbered 10:
#!/bin/sh

MYVAR=`sed -n '10p' myfile.txt`

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "LINUX operating system"

Terms: LINUX operating system