regex - 添加到缺少模式的行的末尾

标签 regex linux bash sed awk

我在 CentOS 上有一个很长的、维护不善的 bash 脚本,其中有许多日志行使用 echo,其中大约三分之一被写入日志文件。我想修改其余的回显行,以便也进入此日志文件。

这里是 myscript.sh 的例子:

command1
echo "hi1"
echo "hi2" | tee -a my.log
echo "hi3 tee"
command2

在这个文件上运行一些东西后,我想把内容改成:

command1
echo "hi1" | tee -a my.log
echo "hi2" | tee -a my.log
echo "hi3 tee" | tee -a my.log
command2

我在想我需要将 sed 或 awk 与正则表达式一起使用,其中的逻辑是,“如果该行包含‘echo’,后跟 not '| tee',然后在行尾附加'| tee -a my.log'。

经过大量搜索,这是迄今为止我想到的最好的:

sed --in-place=_BACKUP '/^.*echo\(?!\| tee$\)*/ s/$/ \| tee -a my.log/' myscript.sh

但这只是附加 | tee -a my.log 到包含 echo 的每一行的末尾。

大家有什么好的想法吗?

最佳答案

这应该可以解决问题(虽然我觉得会出现很多极端情况):

$ awk '/^echo/&&!/tee -a my.log$/{$0=$0"| tee -a my.log"}1' file
command1
echo "hi1"| tee -a my.log
echo "hi2" | tee -a my.log
echo "hi3 tee"| tee -a my.log
command2

解释:

/^echo/                  # If the line start echo
&&                       # Logical AND
!/tee -a my.log$/        # Doesn't end with tee -a my.log
{$0=$0"| tee -a my.log"} # Append the tee command to the end of the line
1                        # Awk idiom to print all the lines in the file

关于regex - 添加到缺少模式的行的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18497645/

相关文章:

linux - 在 linux 中使用 QGLFrameBufferObject 渲染的错误颜色

python - 继续开发已安装的应用程序

bash - 逐字捕获命令行(包括引号!)以调用内部脚本

regex - 从 Hiawatha 移动时出现 FCGI 和 url 问题

Android:replaceAll() 和双引号问题

.net - 正则表达式获取匹配列表

linux - 间接运算符 > 在 bash 中的奇怪行为

bash - 在环境变量中捕获 curl header 和响应

linux - 在 linux 命令行中的一个命令中多次使用 xargs

regex - 多行正则表达式应在文件中匹配多次(如果可能,单行命令)