我在 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/