bash egrep 用新行替换字符串

bash egrep replace string with new line

我需要替换所有出现的

<?php
<?php

成为单身

<?php

现在我有

egrep --include='*.php' -irl '<?php.*\n*.<?php' ./ | xargs sed -i -e "1s/.*//"

但是每次在整个 PHP 文件中找到模式时,egrep 都会替换第一行。

您可以使用 awk:

awk '!(/^<\?php/ && last ~ /^<\?php/);{last = [=10=]}' input.php

如果你想 运行 在当前文件夹中的所有文件上使用 find 的帮助:

find -name '*.php' -exec bash -c '
    file=
    awk "!(/^<\?php/ && last ~ /^<\?php/);{last = $0} " "$file" > "$file.tmp"
    mv "$file.tmp" "$file"
' - '{}' \;

您也可以使用下面的命令(解释见https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string

$ cat file1
<?php
<?php
totototo
tatata

$ cat file2
<?php
blabalbalbalabla

$ sed '/^<?php/{$!{ N;s/^<?php\n<?php/<?php/;ty;P;D;:y}}' file*
<?php
totototo
tatata

<?php
blabalbalbalabla

根据您的用例,这可能会起作用。

uniq input.php

这将抑制所有重复行。但它可能足以满足您的用例。

示例:

> cat example.txt 
alice
alice
bob
alice
alice
bob
alice

> uniq example.txt
alice
bob
alice
bob
alice