bash 将 sed 的输出存储到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6749128/
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-09 20:46:45  来源:igfitidea点击:

Store output of sed into a variable

bash

提问by dogbane

I want to store the second line of my file into a variable, so I am doing this:

我想将文件的第二行存储到一个变量中,所以我这样做:

sed -n '2p' myfile

I wish to store the output of the sedcommand into a variable named line.

我希望将sed命令的输出存储到一个名为line.

What is the correct syntax to do this?

执行此操作的正确语法是什么?

回答by dogbane

Use command substitutionlike this:

像这样使用命令替换

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the =sign.

另请注意,=标志周围没有空间。

回答by Karoly Horvath

In general,

一般来说,

variable=$(command)

or

或者

variable=`command`

The latter one is the old syntax, prefer $(command).

后者是旧语法,首选$(command).

Note: variable = ....means execute the command variablewith the first argument =, the second ....

注意:variable = ....表示variable用第一个参数执行命令=,第二个参数....

回答by tamajit

To store the third line into a variable, use below syntax:

要将第三行存储到变量中,请使用以下语法:

variable=`echo "" | sed '3q;d' urfile`

回答by Adam

line=`sed -n 2p myfile`
echo $line