【问题标题】:Search and replace with grep and perl用 grep 和 perl 搜索和替换
【发布时间】:2018-08-21 08:56:30
【问题描述】:

我需要将下面所有文件中的“vi_chiron”替换为“vi_huracan”。我正在使用以下命令行,并且还将所有底层文件的权限更改为完全访问:

 grep -ri "vi_chiron" ./ | grep -v Header | xargs perl -e "s/vi_chiron/vi_huracan/" -pi

我收到错误: “无法打开 ./build/drivers_file.min:#: 没有这样的文件或目录。 " 和许多其他类似的错误。知道为什么吗?下面是文件的权限:

          ll build/drivers_file.min 
          -rwxrwxrwx 1 ask vi 5860 Mar 13 12:07 build/drivers_file.min

【问题讨论】:

  • 你需要 -l 选项让 grep 只打印文件名...而 grep -v 是排除文件名或带有 Header 的行?

标签: perl unix grep


【解决方案1】:

您可以通过以下方式更改命令:

grep -ril "vi_chiron" . | xargs grep -vl Header | xargs perl -e "s/vi_chiron/vi_huracan/" -pi 

find . -type f -exec grep -ril "vi_chiron" | xargs grep -vl Header | xargs perl -e "s/vi_chiron/vi_huracan/" -pi

为了操作所有不包含Header的文件,把vi_chiron改成vi_hurican

如果我是你,我会简化链条并反过来做:

grep -rvl Header . | xargs sed -i.bak 's/vi_chiron/vi_hurican/'

如果您有足够的信心将 -i.bak 更改为 -i 以便 sed 不进行任何备份。

另请注意,您的更改和替换不是全局的,如果您想全局使用:sed -i.bak 's/vi_chiron/vi_hurican/g'

'-i[SUFFIX]' '--in-place[=SUFFIX]' 此选项指定要就地编辑文件。 GNU 'sed' 通过创建一个临时文件并将输出发送到 这个文件而不是标准输出。(1)。

 This option implies '-s'.

 When the end of the file is reached, the temporary file is renamed
 to the output file's original name.  The extension, if supplied, is
 used to modify the name of the old file before renaming the
 temporary file, thereby making a backup copy(2)).

 This rule is followed: if the extension doesn't contain a '*', then
 it is appended to the end of the current filename as a suffix; if
 the extension does contain one or more '*' characters, then _each_
 asterisk is replaced with the current filename.  This allows you to
 add a prefix to the backup file, instead of (or in addition to) a
 suffix, or even to place backup copies of the original files into
 another directory (provided the directory already exists).

 If no extension is supplied, the original file is overwritten
 without making a backup.

来源:https://www.gnu.org/software/sed/manual/sed.txt

【讨论】:

  • 向你致敬,艾伦。您使用全局替换给出的最后一个命令对我很有用。想知道 sed 如何使用 i.bak 进行备份,以及我们如何在需要时使用它。再次感谢。
  • @user3565150: gnu.org/software/sed/manual/sed.txt 对于整个手册,我已经使用手册页中的 sed 后退选项编辑了我的帖子
  • @user3565150:如果它解决了你的问题,你能把它作为正确答案吗?谢谢!
  • 完成先生!再次感谢
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 2021-01-31
  • 2010-11-13
  • 2017-01-03
  • 2017-01-05
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多