首页 > 解决方案 > 使用 sed 在包含两个特定字符串的行中添加字符

问题描述

我想做这样的事情:

sed "/^[^+]/ s/\(.*$1|$2.*$\)/+\ \1/" -i file

其中在文件中检查了 2 个特定的字符串参数,并且在出现两个参数 ($1 | $2) 的那些行中,如果之前没有 +,则在该行的开头添加一个 +。

到目前为止尝试了不同的变体,最终要么检查两者,然后对包含 2 个字符串中的 1 个或一些错误的每一行进行 sed'ing。感谢有关斜杠和反斜杠转义(分别为单引号/双引号)的任何澄清,我想这就是我的问题所在。

编辑:希望的结果:(包含一堆文本文件的文件夹,其中一个有以下 2 行)

sudo bash MyScript.sh 01234567 Wanted

前:

Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

预期的:

+ Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted. 

标签: linuxstringbashshellsed

解决方案


对于如下所示的输入文件:

$ cat infile
Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

and 设置$1and $2to 01234567and Wanted(在脚本中,这些只是前两个位置参数,不必设置):

$ set -- 01234567 Wanted

以下命令将起作用:

$ sed '/^+/b; /'"$1"'/!b; /'"$2"'/s/^/+ /' infile
+ Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

这是它的工作原理:

sed '
    /^+/b           # Skip if line starts with "+"
    /'"$1"'/!b      # Skip if line doesn't contain first parameter
    /'"$2"'/s/^/+ / # Prepend "+ " if second parameter is matched
' infile

b是“分支”命令;单独使用时(与要跳转到的标签相反),它会跳过所有命令。

前两个命令跳过以第一个参数开头+或不包含第一个参数的行;如果我们在s命令的行上,我们已经知道当前行不是以第一个参数开头+并且包含第一个参数。如果它包含第二个参数,我们在前面加上+ .

对于引用,我单引号引用了整个命令,但包含参数的位置除外:

'single quoted'"$parameter"'single quoted'

所以我不必逃避任何不寻常的事情。这假定双引号部分中的变量不包含任何可能混淆 sed 的元字符。


推荐阅读