简体   繁体   English

我想在shell脚本的sed -f命令中使用变量

[英]i want to use variable in sed -f command in shell script

I am using this command to copy certain line from one file to another.Its working fine.No issue with it. 我正在使用此命令将某些行从一个文件复制到另一个文件,它工作正常,没有问题。

sed -f <(sed -e '1,10d; 12,$d; x; s/.*/10a\\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

The problem is instead of 10, I want to use variable VAR1 (where var1=10). 问题是不是10,而是要使用变量VAR1(其中var1 = 10)。 The $VAR1 is not working. $ VAR1无法正常工作。

I tried this command. 我试过这个命令。

sed -f <(sed -e '1,$VAR1d; 12,$d; x; s/.*/10a\\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

Please help me. 请帮我。

At first, use double quotes. 首先,使用双引号。 It will enable BASH to process string. 这将使BASH能够处理字符串。

Next, escape backslashes (even those that supposed to be escape symbols for sed) - because bash will escape them too. 接下来,转义反斜杠(甚至那些应该用作sed的转义符号的反斜杠)-因为bash也将其转义。

I suppose it should be 我想应该是

sed -f <(sed -e "1,${VAR1}d; 12,\$d; x; s/.*/10a\\\\/;p; x" ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

尝试双qoutes和花括号:

 sed -f <(sed -e "1,${VAR1}d; 12,\$d; x; s/.*/10a\\\\/;p; x" ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

I prefer mix of single & double quotes: 我更喜欢单引号和双引号的混合使用:

  1. Single quotes around the text that must not be expanded. 不得在文本周围加上单引号。 (Removes need to escape special characters.) (删除时需要转义特殊字符。)
  2. Double quotes around the text that needs to be expanded. 需要扩展的文字周围用双引号引起来。

eg Your case would look like: 例如,您的情况如下:

sed -f <(sed -e '1,'"$VAR1"'d; 12,$d; x; s/.*/10a\\/;p; x' ../log/file2.txt ) ../log/file4.txt > ../log/file5.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM