将 sed 的输出存储到一个变量中

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

sed -n '2p' myfile

我希望将 sed命令的输出存储到一个名为 line的变量中。

这样做的正确语法是什么?

149640 次浏览

In general,

variable=$(command)

or

variable=`command`

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

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

Use command substitution like this:

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

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

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

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

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

To store the changed line into a variable, use below syntax: variable=echo 'overflow' | sed -e "s/over/"OVER"/g" output:OVERflow