bash - 如何使用 sed 在特定单词后添加单引号?
问题描述
我正在尝试编写一个脚本以在 "GOOD" word 之后添加单引号。例如,我有 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
提前感谢您的帮助!
解决方案
请您尝试以下操作。
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.
-i
如果您想将输出保存到 Input_file 本身,请使用上述代码中的选项。
第二种解决方案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,1,RSTART) "\047" substr($0,RSTART+1,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.
推荐阅读
- docker - 重定向 Jenkins Pipeline Docker 插件的日志输出
- python - 从 URL 读取视频文件并使用 OpenCV 对其进行解析
- css - 交叉点观察者 API 和溢出隐藏
- vbscript - ASP Classic 中的 DateAdd 函数如何与“ww”周选项一起使用?
- mysql - 如何通过Pentaho水壶有效地将大型数据集从调用过程(表输入)加载到目标表?
- android - Aapt2 抛出先前构建中存在的错误
- regex - 在 Clojure 中忽略大小写敏感
- events - 如何在 Angular 2+ 中使用 HostListener 防止窗口关闭事件
- oracle - 在 Collections 中动态获取数据
- java - 循环和 showConfirmDialog