仅当当前行中存在字符串时才替换 [英] Replace only if string exists in current line
问题描述
我有一行,例如:
sed -i 's/mystring/newstring/' $target
此命令会将所有mystring
更改为newstring
.
This command will change all mystring
to newstring
.
我现在想要的是:当程序看到mystring
时,如何检查字符串searchstring
是否存在的当前行?如果存在,则newstring
是1
;否则,newstring
是0
.
What I want now is: when the program sees mystring
, how can I check for the current line if the string searchstring
exists or not? If it exists, newstring
is 1
; otherwise, newstring
is 0
.
推荐答案
解决方案
假设您的输入文件$ target包含以下内容:
Solution
Assuming your input file $target contains the following:
some text mystring some other text
some text mystring a searchstring
just some more text
此命令:
sed -i -e '/searchstring/ s/mystring/1/ ; /searchstring/! s/mystring/0/' $target
会将其内容更改为:
some text 0 some other text
some text 1 a searchstring
just some more text
说明
该脚本包含两个用分号分隔的替代( s )命令.
替代命令接受一个可选的地址范围,该范围选择应进行替代的行.
The substitute command accepts an optional address range that select which lines the substitution should take place.
在这种情况下, regexp 地址用于为第一个命令选择包含 searchstring 的行;以及第二行中不包含 searchstring (注意正则表达式匹配后的感叹号)的行.
In this case regexp address was used to select lines containing the searchstring for the first command; and the lines that do not contain the searchstring (note the exclamation mark after the regexp negating the match) for the second one.
此命令将更好地执行并产生相同的结果:
This command will perform better and produce just the same result:
sed -i -e '/searchstring/ s/mystring/1/ ; s/mystring/0/' $target
重点是命令是按顺序执行的,因此,如果在第一条命令完成后,当前行中的 mystring 子字符串仍然存在,则没有肯定是其中的搜索字符串.
The point is that commands are executed sequentially and thus if there is still a mystring substring in the current line after the first command finished then there is no searchstring in it for sure.
对user946850表示敬意.
Kudos to user946850.
这篇关于仅当当前行中存在字符串时才替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!