用grep和perl搜索并替换

时间:2018-03-13 07:26:12

标签: perl unix grep

我需要从下面的所有文件中将“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

1 个答案:

答案 0 :(得分:3)

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

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 -i.bak 's/vi_chiron/vi_hurican/g'代替。

  

' -i [SUFFIX]' ' - 在就地[= 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

相关问题