如何在Linux sed命令中使用变量

时间:2021-09-18 12:33:47

I have already read some topic but there is no similar to mine.

我已经阅读了一些主题,但与我的相似。

I need to pass to sed command with a $value but its too hard :

我需要使用$ value传递给sed命令,但它太难了:

sed "1,$valued" filename.txt

like

sed "1,4d" filename.txt

How can i do that ?

我怎样才能做到这一点 ?

2 个解决方案

#1


That's trying to use a variable called $valued.

那是试图使用一个名为$ valued的变量。

So you can either:

所以你可以:

1,${value}d.

Or set $valued to 4d.

或者将$ value设置为4d。

#2


Easiest way:

sed "1,$value"d filename.txt

$value is a shell variable (I assume you were already doing that). So you just needed a way to separate the variable name from what comes next (to avoid evaluating $valued). Quote marks do the job just fine since the shell removes them before calling sed.

$ value是一个shell变量(我假设你已经这样做了)。所以你只需要一种方法将变量名与下一个变量名分开(以避免评估$ values)。由于shell在调用sed之前删除它们,因此引用标记可以正常工作。

#1


That's trying to use a variable called $valued.

那是试图使用一个名为$ valued的变量。

So you can either:

所以你可以:

1,${value}d.

Or set $valued to 4d.

或者将$ value设置为4d。

#2


Easiest way:

sed "1,$value"d filename.txt

$value is a shell variable (I assume you were already doing that). So you just needed a way to separate the variable name from what comes next (to avoid evaluating $valued). Quote marks do the job just fine since the shell removes them before calling sed.

$ value是一个shell变量(我假设你已经这样做了)。所以你只需要一种方法将变量名与下一个变量名分开(以避免评估$ values)。由于shell在调用sed之前删除它们,因此引用标记可以正常工作。