【问题标题】:Look for a substring in a file and comment that line and insert new line underneath the commented line在文件中查找子字符串并注释该行并在注释行下方插入新行
【发布时间】:2021-07-26 02:30:31
【问题描述】:

我正在尝试在文件中查找子字符串--port 1234,如果该行没有被注释,则用# 注释掉该行,并在其下方插入一个定义为this is the new path: /new/path/to/file 的新行。如果包含--port 1234 的行已被注释,则什么也不做。如果在文件中找不到子字符串--port 1234,则echo "not found"

示例输入:

somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode

样本输出:

somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode

这是我目前所拥有的:

sed -E '/--port 1234/!b;/^[^#]/!b;

到目前为止,我只知道如果该行已经被注释,或者如果一行不包含--port 1234,如何忽略它。对 bash 脚本非常陌生!

【问题讨论】:

  • 你总是问同样的问题herehere。自己尝试,当您无法解决问题时来这里。

标签: bash unix awk sed grep


【解决方案1】:

awk更适合这份工作。

示例文件:

cat file

foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode

gnu awk 用作:

awk -i inplace '/--port 1234 / && !/^#/ {
   print "#" $0 ORS "This is the new path: /new/path/to/file"
   next
} 1' file

foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode

【讨论】:

  • 它只是在终端打印出输出(虽然正确),但文件没有改变。我想自己编辑文件!
  • 你的 awk 版本是多少?检查awk -V
  • 3.1.7 是我的 GNU awk
  • 原地不兼容3.1.7。请问可以用sedgrep吗?
  • 然后使用:awk '/--port 1234/ && !/^#/ {print "#" $0 ORS "This is the new path: /new/path/to/file"; next} 1' file > file.tmp && mv file.tmp file
【解决方案2】:

坚持sed 理念:

示例输入,带和不带前导注释 (#):

$ cat myfile
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode

一个sed想法:

$ sed -E 's|^([^#].*--port 1234.*)$|#\1\nThis the new path: /new/path/to/file|' myfile
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This the new path: /new/path/to/file
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode

一旦 OP 对结果感到满意,就可以添加 -i 标志来执行文件的就地更新。

【讨论】:

  • 这是一个很好的解决方案,但如果我第二次发出sed command,This the new path: /new/path/to/file 会再次打印。我不想要那个。您能否通过 grep 或 if 条件在您的解决方案中解决这个问题?
  • 我误读了关于该行之前被注释掉的部分;答案已更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 2023-02-02
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2021-07-30
  • 2018-11-22
相关资源
最近更新 更多