如何使用sed在特定单词后添加单引号?

我正在尝试编写一个脚本,在“ GOOD”一词后添加单引号。 例如,我有file1:

//WER GOOD=ONE //WER1 GOOD=TWO2 //PR1 GOOD=THR45 ...

所需的更改是添加单引号:

//WER GOOD='ONE' //WER1 GOOD='TWO2' //PR1 GOOD='THR45' ...

这是我要运行的脚本:

#!/bin/bash

for item in `grep "GOOD" file1 | cut -f2 -d '='`

do

sed -i 's/$item/`\$item/`\/g' file1

done 

谢谢您的帮助!

bluegame111111 回答:如何使用sed在特定单词后添加单引号?

请您尝试以下。

sed "s/\(.*=\)\(.*\)/\1'\2'/"  Input_file

或根据OP的注释删除空行使用:

sed "s/\(.*=\)\(.*\)/\1'\2'/;/^$/d"  Input_file

说明: 以下内容仅出于解释目的。

sed "              ##Starting sed command from here.
s/                 ##Using s to start substitution process from here.
\(.*=\)\(.*\)      ##Using sed buffer capability to store matched regex into memory,saving everything till = in 1st buffer and rest of line in 2nd memory buffer.
/\1'\2'            ##Now substituting 1st and 2nd memory buffers with \1'\2' as per OP need adding single quotes before = here.
/"  Input_file     ##Closing block for substitution,mentioning Input_file name here.

如果要将输出保存到Input_file本身,请在上面的代码中使用-i选项。



使用awk的第二个解决方案:

awk 'match($0,/=.*/){$0=substr($0,1,RSTART) "\047" substr($0,RSTART+1,RLENGTH) "\047"} 1' Input_file

说明: 添加上述代码的说明。

awk '
match($0,/=.*/){                                                     ##Using match function to mmatch everything from = to till end of line.
  $0=substr($0,RLENGTH) "\047"   ##Creating value of $0 with sub-strings till value of RSTART and adding ' then sub-strings till end of line adding ' then as per OP need.
}                                                                    ##Where RSTART and RLENGTH are variables which will be SET once a TRUE matched regex is found.
1                                                                    ##1 will print edited/non-edited line.
' Input_file                                                         ##Mentioning Input_file name here.


第三种解决方案: :如果Input_file中只有2个字段,请尝试在awk中更简单:

awk 'BEGIN{FS=OFS="="} {$2="\047" $2 "\047"} 1' Input_file

第三个​​代码的解释: 仅用于说明目的,为了运行,请使用上面的代码本身。

awk '                    ##Starting awk program here.
BEGIN{FS=OFS="="}        ##Setting FS and OFS values as = for all line for Input_file here.
{$2="\047" $2 "\047"}    ##Setting $2 value with adding a ' $2 and then ' as per OP need.
1                        ##Mentioning 1 will print edited/non-edited lines here.
' Input_file             ##Mentioning Input_file name here.
本文链接:https://www.f2er.com/3115313.html

大家都在问