【问题标题】:text processing: find multiple words split by newline文本处理:查找由换行符分割的多个单词
【发布时间】:2015-10-03 22:42:09
【问题描述】:

如何在不删除换行符的情况下找到可能被换行符分割的多个单词?

例如

The promotion and merchandise aided the success of We Are
the World and raised over $63 million for humanitarian
aid in Africa and the US.

使用 sed(或任何 *nix 文本处理工具,例如 awk、perl)搜索 We Are the World 并将其替换为例如<song title> 所以它显示为:

The promotion and merchandise aided the success of <song title>
and raised over $63 million for humanitarian
aid in Africa and the US.

我有一堆搜索模式(歌曲标题),我想搜索文本片段并将它们全部替换为 &lt;song title&gt;。我不想删除换行符。

【问题讨论】:

    标签: regex replace sed


    【解决方案1】:
    $ cat tst.awk
    BEGIN { gsub(/ +/,"[[:space:]]+",old); old = tolower(old) }
    { tail = tail $0 RS }
    END {
        head = ""
        while ( match(tolower(tail),old) ) {
            trgt = substr(tail,RSTART,RLENGTH)
            head = head substr(tail,1,RSTART-1) new
            tail = substr(tail,RSTART+RLENGTH)
            if (trgt ~ RS) {
                head = head RS
                sub(/^[[:blank:]]+/,"",tail)
            }
        }
        printf "%s%s", head, tail
    }
    
    $ awk -v old='we are the world' -v new='<song title>' -f tst.awk file
    The promotion and merchandise aided the success of <song title>
    and raised over $63 million for humanitarian
    aid in Africa and the US.
    

    以上假设您处理旧歌名中的换行符的要求是将该换行符附加到新歌名的末尾,并删除旧歌名后面的所有空白字符。

    【讨论】:

    • 你可能想用你输入的一些其他变体来测试它,看看你是否有任何不同的需求需要处理,例如旧歌曲名称中的多个换行符,旧歌曲名称包含换行符,但后面是标点符号而不是空格。等等,等等。如果老歌的名字是一个普通的词或短语,比如“Pure”——你怎么知道你是在替换一个歌名还是一个词“Lightning Seed的歌曲Pure很好。纯艺术!”。我让我的所有测试都不区分大小写 - 也许这不是你想要的,但我认为你需要它。
    • 你是对的,在一般情况下应该记住这一点。在我的情况下,“歌曲”都是唯一的字符串,不会显示为常规文本。是的,不要求区分大小写,但确实很有用。
    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2012-03-06
    • 2015-04-21
    相关资源
    最近更新 更多