使用bash脚本删除文件中的第一个内容块

时间:2017-09-21 21:27:32

标签: bash

我有一个包含200行代码的文件。应使用<?php?>标记删除以<?php开头且以?>结尾的第一段。以下是该文件的示例:

<?php
    some random code that should be removed
    ....
    ....
    ....

?><?php /*The beginning of the new <?php Tag is important and have to stay in the file!*/
  important code
   ....
   ....
   ....
   ....
?>

有没有办法用bash删除文件中的第一个<?php ?>块?如果我使用tail,我只得到文件的最后一部分,因为每次使用它都不一样,代码行数不同..

2 个答案:

答案 0 :(得分:0)

cat通过这个管道:

sed 's/^\(?>\)/\1\n/' | sed '1,/^?>$/d'

第一个sed将单行?><?php /*The beginning...分成两行。这对于第二个sed很方便,它只是删除了初始代码块。两个正则表达式都集中在?>块结束标记。

如果您希望避免使用sed,则第二个sed可能会替换为perl -ne 'print unless 1../^\?>$/'

答案 1 :(得分:0)

使用GNU awk:

$ awk 'BEGIN{ORS=RS="?>"} NR>1{print}' file
<?php /*The beginning of the new <?php Tag is important and have to stay in the file!*/
  important code
   ....
   ....
   ....
   ....
?>

解释:

BEGIN { ORS=RS="?>" } # set input and output record separators to php closing tag
NR>1 { print }        # output tag ending record starting from the second

如果常量等?>,则会失败。您可以尝试用ORS=RS="\n?>"来绕过它。