Regex 文本处理:查找按换行符拆分的多个单词

Regex 文本处理:查找按换行符拆分的多个单词,regex,replace,sed,Regex,Replace,Sed,如何在不删除换行符的情况下查找可能被换行符拆分的多个单词 例如 使用sed(或任何*nix文本处理工具,如awk、perl)搜索我们是世界,并将其替换为,使其显示为: The promotion and merchandise aided the success of <song title> and raised over $63 million for humanitarian aid in Africa and the US. 促销和商品有助于 为人道主义援助筹集了6300多

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

例如

使用sed(或任何*nix文本处理工具,如awk、perl)搜索
我们是世界
,并将其替换为
,使其显示为:

The promotion and merchandise aided the success of <song title>
and raised over $63 million for humanitarian
aid in Africa and the US.
促销和商品有助于
为人道主义援助筹集了6300多万美元
对非洲和美国的援助。
我有一系列的搜索模式(歌曲标题),我想搜索文本片段并用
替换它们。我不想删除换行符。

$cat tst.awk
$ 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.
开始{gsub(+/+/,“[[:space:]+”,old;old=tolower(old)} {tail=tail$0rs} 结束{ head=“” while(匹配(tolower(tail)、old)){ trgt=substr(尾部,起始,长度) head=头部substr(尾部,1,RSTART-1)新 tail=substr(tail,RSTART+RLENGTH) if(trgt~RS){ 水头=水头 子(/^[:空白:]+/,“”,尾部) } } 打印文件“%s%s”,头部、尾部 } $awk-v old='我们是世界'-v new=''''-f tst.awk文件 促销和商品有助于这次活动的成功 为人道主义援助筹集了6300多万美元 对非洲和美国的援助。

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

您可能希望使用输入的其他变体对其进行测试,看看是否有任何需要处理的不同要求,例如,旧歌曲名称中有多个换行符,旧歌曲名称包含一个换行符,但后跟标点符号而不是空格。等等,等等。如果老歌名是一个普通的词或短语,比如“Pure”——你怎么知道你是在替换一个歌名,还是仅仅是一个词“闪电种子的歌很好,纯艺术!”。我对所有测试都不区分大小写-也许这不是你想要的,但我认为你需要它。你是对的,在一般情况下,这应该记住。在我的例子中,“歌曲”都是唯一的字符串,不会显示为常规文本。是的,没有要求区分大小写,但确实很有用。
$ 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.