我想做这样的事情:
sed "/^[^+]/ s/\(.*$1|$2.*$\)/+\ \1/" -i file
在文件中检查2个特定的字符串参数的位置,并且在出现两个参数($ 1 | $ 2)的那些行中,如果之前没有+,则在该行的开头添加+。
到目前为止,我们尝试了不同的变体,最后都检查了两者,然后对包含2个字符串之一或某些错误的每一行进行sed处理。感谢您对斜杠和反斜杠转义的说明(分别是单引号/双引号),我想这就是我的问题所在。
编辑:希望的结果:(包含一堆文本文件的文件夹,其中有以下两行)
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.
对于看起来如下的输入文件:
$ 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混淆的元字符。