Linux sed在bash中使用变量取消注释多行
我有以下问题:我试图从我确定使用的特定行取消注释:Linux sed在bash中使用变量取消注释多行,linux,unix,awk,Linux,Unix,Awk,我有以下问题:我试图从我确定使用的特定行取消注释: LINESTART=$(grep -nr "matching string" test.conf | cut -d : -f1) 在此之后,我需要取消对代码部分的注释,从$LINESTART到$((行+10)) 我尝试了以下sed语法: sed -i '${LINESTART},${LINEEND} s/# *//' test.conf 但我得到了以下错误: sed: -e expression #1, char 4: extra char
LINESTART=$(grep -nr "matching string" test.conf | cut -d : -f1)
在此之后,我需要取消对代码部分的注释,从$LINESTART
到$((行+10))
我尝试了以下sed语法:
sed -i '${LINESTART},${LINEEND} s/# *//' test.conf
但我得到了以下错误:
sed: -e expression #1, char 4: extra characters after command
示例test.conf:
84 #server {
85 # listen 8000;
86 # listen somename:8080;
87 # server_name somename alias another.alias;
88
89 # location / {
90 # root html;
91 # index index.php index.html index.htm;
92 # }
93 #}
在单引号中使用shell变量可以防止它们被值替换。相反,使用双引号应该可以实现您想要的:
$ cat file
# a0
# a1
# a2
# a3
$ S=2
$ E=3
$ sed "${S},${E}s/# *//" file
# a0
a1
a2
# a3
你能试试这个吗
sed -i "${LINESTART},${LINEEND} s/# *//" test.conf
试验
脚本:
#!/bin/bash
LINESTART=$(grep -nr "server {" test | cut -d : -f1 )
LINEEND=$((LINE+10))
sed "${LINESTART},${LINEEND} s/# *//" test
输出:
$ ./test.sh
server {
listen 8000;
listen somename:8080;
server_name somename alias another.alias;
location / {
root html;
index index.php index.html index.htm;
}
}
不要这样做,只需使用awk来完成整个过程:
$ awk '/location/{c=4} c&&c--{sub(/# */,"")} 1' file
84 #server {
85 # listen 8000;
86 # listen somename:8080;
87 # server_name somename alias another.alias;
88
89 location / {
90 root html;
91 index index.php index.html index.htm;
92 }
93 #}
查找文件btw的命令名为find
,而不是grep-r
,正如GNU sed具有用于就地编辑的-i
,如果需要,GNU awk具有-i inplace
,因此这可能是您真正想要的:
$ find . -name 'file' -exec \
awk -i inplace '/location/{c=4} c&&c--{sub(/# */,"")} 1' {} \;
注意像
${LINESTART}
这样的bash变量在单引号内时不会被它们的值替换。LINEEND=$((LINE+10))应该更改为LINEEND=$((LINESTART+10))顺便说一句,不需要$LINEEND
-您可以使用sed-i'${LINESTART},+10…
)LINEEND=$((第+10行))应更改为LINEEND=$((第+10行))
$ find . -name 'file' -exec \
awk -i inplace '/location/{c=4} c&&c--{sub(/# */,"")} 1' {} \;