bash 如何使用 sed 从文件中打印行,其中行号存储为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16326663/
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
How to print lines from a file using sed, where the line numbers are stored as variables
提问by bytesahoy
I am trying to print out a specific section of a file which I have determined using line numbers, but the line numbers will vary from day to day so I need to be able to get the line numbers, store them as variables, then use sed to cut the lines from the stored file.
我正在尝试打印出我使用行号确定的文件的特定部分,但行号每天都会有所不同,因此我需要能够获取行号,将它们存储为变量,然后使用 sed从存储的文件中剪切行。
Here's what I have so far:
这是我到目前为止所拥有的:
start-loader is a file that contains the lines I want to print, but also contains a lot of junk.
start-loader 是一个文件,其中包含我要打印的行,但也包含很多垃圾。
I can use sed -n '93,109p' start-loaderto print out what I need, but what I want to do is this:
我可以sed -n '93,109p' start-loader用来打印出我需要的东西,但我想做的是:
sed -n '$FL,$LFp' start-loader
where the variables are the line numbers I've stored.
其中变量是我存储的行号。
I know that the above is not proper syntax, from a lot of research on the matter, but everything I've used either returns an error or does not work. I've tried double quotes, single then double for variables, braces for variables, and a few other things along with numerous different syntax styles. Would anyone happen to know how I can properly do this?
我知道以上不是正确的语法,从对此事的大量研究来看,但我使用的所有内容要么返回错误,要么不起作用。我尝试过双引号,变量的单引号,变量的双引号,变量的大括号以及其他一些东西以及许多不同的语法样式。有人会碰巧知道我如何正确地做到这一点吗?
回答by chepner
You need to separate the pcommand from your last-line variable somehow. Either of the following should work:
您需要以p某种方式将命令与最后一行变量分开。以下任何一项都应该有效:
$ sed -n "$FL,${LF}p" start-loader
$ sed -n "$FL,$LF p" start-loader
Without the separation, the shell would try to expand the variable LFp, which does not exist, resulting in an empty string being passed to sedand causing a syntax error.
如果没有分离,shell 会尝试扩展LFp不存在的变量,导致传递给空字符串sed并导致语法错误。
You also need to use double-quotes, not single-quotes, to allow the variables to be expanded before sedsees them.
您还需要使用双引号,而不是单引号,以允许在sed看到变量之前对其进行扩展。
回答by Kent
I hope the example below answered your question:
我希望下面的例子回答了你的问题:
kent$ s=3
kent$ e=8
kent$ seq 20 |sed -n "$s,$e p"
3
4
5
6
7
8

