z=6 # focus line
x=4 # lines before
y=3 # lines after
start=$(( z - x ))
end=$(( z + y ))
Using sed:
seq 10 | sed -n "$start,${end}p"
2
3
4
5
6
7
8
9
This simply uses the print (p) command of sed with a explicit range of lines to print. The other lines are ignored using -n.
Using awk:
seq 10 | awk -v start="$start" -v end="$end" 'NR >= start { print } NR >= end { exit }'
2
3
4
5
6
7
8
9
This is similar to Stéphane Chazelas' answer, but implemented in awk; the script starts outputting the input lines after having read start number of lines. At end number of lines, the script exits.
Both alternatives will display a portion of the input data, starting at x lines before the line z and ending y lines after line z.
printf %s\\n {1..20} | sed -n 5,15p– Satō Katsura May 28 '17 at 06:26If line number is 6What decide it is line 6? Do you search for a word or something? This lineseq 10 | grep -B4 -A3 "6"will search for a line which matches"6"and print 4 lines before and 3 lines after. – hschou May 28 '17 at 08:15