繁体   English   中英

删除仅从文件第一行开始的多行模式

[英]Delete multi-line pattern starting on first line of file only

我正在尝试从Bash脚本中删除文件,如下所示:

<%
delete this tag
%><? keep this tag ?>
<% keep this tag %>

但仅当该标记位于文件的开头时,以下内容才会被修改:

text to keep
<%
don't delete me now
%>

我试图从其他问题的答案中整理出一些东西,但是还没有想到可以像这样工作的命令。

sed是否可能? 是否有其他工具更有效?

如果您想给perl一个机会,那么应该可以:

perl -0777 -pe 's/^\s*<%.*?%>//s' file

<? keep this tag ?>
<% keep this tag %>

分手:

  • -0777-0777模式以匹配所有文件文本,包括换行符
  • ^\\s* :匹配开始,后跟0或多个空格
  • <%.*?%> :匹配您的标签(惰性)

要将更改保存回文件:

perl -i -0777 -pe 's/^\s*<%.*?%>//s' file

使用awk:

$ awk '
NR==1 && /</ { d=1 }     # if < on the first line raise the del flag
d==1 {                   # if del flag up
    if(/>/)              # lower del flag at >
        d=0              
    sub(/<?[^>]+>?/,"")  # replace from < to > with nuthin
} 
/./                      # print nonempty lines
' file
<? keep this tag ?>
<% keep this tag %>

处理的另一个文件:

text to keep
<%
don't delete me now
%>

您应该使用sed ,例如:

sed '0,/REGEXP/' your_input_file

REGEXP是您所需的正则表达式。

因此,发布后,我想出了如何使用以下命令在sed执行此操作:

sed -e '/<%/{1!b;:x;$!N;/%>/!bx;s/<%.*%>//}' -i "file"

命令说明:

sed -e
    '/<%/           # When we match the start pattern, '<%', execute the following command block
    {
        1!b;        # If we're not on the first line when we match the start pattern, exit
        :x;         # Define label 'x'
        $!N;        # If not at the end of file, capture the current line
        /%>/!bx;    # If we're not at the end pattern, '%>', go to label 'x'
        s/<%.*%>//  # After reaching the end pattern, replace all matching text in the captured lines with nothing
    }'
    -i "file"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM