仅当当前行中存在字符串时才替换 [英] Replace only if string exists in current line

查看:97
本文介绍了仅当当前行中存在字符串时才替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行,例如:

sed -i 's/mystring/newstring/' $target

此命令会将所有mystring更改为newstring.

This command will change all mystring to newstring.

我现在想要的是:当程序看到mystring时,如何检查字符串searchstring是否存在的当前行?如果存在,则newstring1;否则,newstring0.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆