bash sed:如何打印到文件末尾的行范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32889645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:40:00  来源:igfitidea点击:

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

bashsed

提问by JosephSmith47

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

我可以使用此 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

sed: 1: "267975,": 预期的上下文地址

回答by edi9999

You're the victim of Shell Parameter Expansion

你是Shell 参数扩展的受害者

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

is received by sedas

被接收sed

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

because the pvariable is undefined.

因为p变量未定义。

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.htmlFor the full list of existing shell expansions.

有关现有 shell 扩展的完整列表,请参阅https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html

回答by jessup Hymanson

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

在范围的开始/结束作为变量传递给 sed 的情况下,单引号响应不起作用。

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

在单引号中的结束符号 $ 和 p 之间包含一个空格适用于我的系统,以防止 $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 的扩展需要双引号,因此空格通常是一个好主意:

L1=267975
sed -n "${L1},$ p" ${INPUT_FILE} > dump${L1}