Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: how to print a range of line to end of file

Tags:

bash

sed

I can print a range of lines from a file using this cmd:

sed -n 267975,1000000p < dump-gq1-sample > dump267975

but how to print to the end? I tried

sed -n 267975,$p < dump-gq1-sample > dump267975

and it gives me:

sed: 1: "267975,": expected context address

like image 287
JosephSmith47 Avatar asked Oct 01 '15 14:10

JosephSmith47


2 Answers

You're the victim of Shell Parameter Expansion

sed -n 267975,$p < dump-gq1-sample > dump267975

is received by sed as

sed -n 267975, < dump-gq1-sample > dump267975

because the p variable is undefined.

You should quote your parameter with single quotes '

sed -n '267975,$p' < dump-gq1-sample > dump267975

See https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html For the full list of existing shell expansions.

like image 130
edi9999 Avatar answered Oct 27 '22 05:10

edi9999


the single-quote response does not work in cases where the start/end of range are passed to sed as a variable.

including a space between the end-symbol $ and p in single quotes works on my systems to prevent unintended expansion of $p

sed -n '267975,$ p' ${INPUT_FILE} > ${OUTPUT_FILE} #double quotes work here too

If you need to pass the initial line as a variable, double quotes are required for the expansion of $L1 so the space is generally a good idea:

L1=267975
sed -n "${L1},$ p" ${INPUT_FILE} > dump${L1}
like image 31
jessup jackson Avatar answered Oct 27 '22 05:10

jessup jackson