我想做这样的事情:
sed "/^[^+]/ s/\(.*$1|$2.*$\)/+\ \1/" -i file
在文件中检查 2 个特定的字符串参数,并且在出现两个参数 ($1 | $2) 的行中,如果之前没有 +,则在行的开头添加一个 +。
到目前为止尝试了不同的变体,最终要么检查两者,要么检查包含 2 个字符串中的 1 个的每一行或一些错误。 感谢有关斜杠和反斜杠转义(分别是单引号/双引号)的任何澄清,我想这就是我的问题所在。
编辑:希望的结果:(包含一堆文本文件的文件夹,其中一个具有以下 2 行)
sudo bash MyScript.sh 01234567 Wanted
之前:
Some Random Text And A Number <b>01234567</b> and i'm <b>Wanted</b>.
Another Random Text with Diff Number 09812387 and i'm still <b>Wanted</b>.
预期:
+ Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.
最佳答案
对于如下所示的输入文件:
$ 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.
并将 $1
和 $2
设置为 01234567
和 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 混淆的元字符。
关于linux - 使用 sed 在包含两个特定字符串的行中添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59271355/