linux - 使用 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.
解决方案
对于如下所示的输入文件:
$ 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 设置$1
and $2
to 01234567
and 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 的元字符。
推荐阅读
- python - 如何在轴'y'python数据框中绘制小时数
- compiler-construction - LLVM的内存依赖分析上下文中的“clobbers”是什么意思
- java - Java - 将 ArrayList 调用到另一个类
- asp.net-web-api - 无法从网络上的远程计算机访问 ASP.NET Core API
- javascript - 动画在打开购物车抽屉时工作一次,然后就不再工作
- php - 如何回显数据库中的项目
- java - 从文本文件写入时,数组只会将值设置为“0”
- c++ - 错误:从 'std::__1::basic_string 没有可行的转换
' 到 'const QString' - jupyter-notebook - 如何修复 JupyterLab 中 markdown 文件的文件加载错误
- java - 在 Java 中使用时区转换时出现奇怪的结果