Issue
How to output N(e.g. 2) lines surrounding a specific known line number(e.g. 5) in a file?
cat >/tmp/file <<EOL
foo
bar
baz
qux
quux
EOL
# some command
Expected output:
bar
baz
qux
Solution
If you know the line and number of lines in advance and thus you are able to compute the number of the first line and number of the last line you might use simple GNU sed
command, for example
sed -n '3,7p' file.txt
will output 3rd, 4th, 5th, 6th and 7th line of file.txt
.
If you wish to change the line number then I would use GNU AWK
following way
awk 'BEGIN{n=5}NR==n-2,NR==n+2' file.txt
Explanation: I set n to 5 then I use Range to select lines from n-2
th line (inclusive) to n+2
th line (inclusive), no action is provided which is equivalent of giving {print}
.
Answered By - Daweo Answer Checked By - David Goodson (WPSolving Volunteer)