bash egrep用新行替换字符串

时间:2016-02-15 13:05:56

标签: bash replace grep newline

我需要替换所有出现的

<?php
<?php

成为单身

<?php

现在我有

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

但是当每个在整个PHP文件中找到模式时,egrep会替换FIRST行。

3 个答案:

答案 0 :(得分:0)

您可以使用awk

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

如果要在当前文件夹中的所有文件上运行该文件,请使用find的帮助:

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

答案 1 :(得分:0)

您也可以使用以下命令(请参阅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

答案 2 :(得分:0)

这可能取决于您的用例。

uniq input.php

这将禁止所有重复行。但这可能足以满足您的用例。

示例:

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

> uniq example.txt
alice
bob
alice
bob
alice