使用全包通配符查找和替换文本

时间:2015-08-23 09:28:39

标签: replace sed find wildcard

我有一个这样的文件:

foo and more
stuff
various stuff
variable number of lines
with a bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important

我想替换foo和bar之间的所有内容,以便我得到:

foo testtext bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important

在我尝试的另一个线程中推荐:     sed -e '/^foo/,/^bar/{/^foo/b;/^bar/{i testtext' -e 'b};d}' file.txt

是否有更通用的解决方案来查找和替换foobar之间的所有内容,无论它是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用以下sed脚本:

replace.sed:

# Check for "foo"
/\bfoo\b/    {   
    # Define a label "a"
    :a  
    # If the line does not contain "bar"
    /\bbar\b/!{
        # Get the next line of input and append
        # it to the pattern buffer
        N
        # Branch back to label "a"
        ba
    }   
    # Replace everything between foo and bar
    s/\(\bfoo\)\b.*\b\(bar\b\)/\1TEST DATA\2/
}

这样称呼:

sed -f extract.sed input.file

输出:

fooTEST DATAbar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important

如果你想使用shell脚本传递开始和结束分隔符,你可以这样做(为简洁起见删除了注释):

#!/bin/bash

begin="foo"
end="bar"

replacement=" Hello world "

sed -r '/\b'"$begin"'\b/{
    :a;/\b'"$end"'\b/!{
        N;ba
    }
    s/(\b'"$begin"')\b.*\b('"$end"'\b)/\1'"$replacement"'\2/
}' input.file

只要$start$end不包含正则表达式特殊字符{},to escape them properly使用以下代码,上述工作就会起作用:

#!/bin/bash

begin="foo"
end="bar"
replace=" Hello\1world "

# Escape variables to be used in regex
beginEsc=$(sed 's/[^^]/[&]/g; s/\^/\\^/g' <<<"$begin")
endEsc=$(sed 's/[^^]/[&]/g; s/\^/\\^/g' <<<"$end")
replaceEsc=$(sed 's/[&/\]/\\&/g' <<<"$replace")

sed -r '/\b'"$beginEsc"'\b/{
    :a;/\b'"$endEsc"'\b/!{
        N;ba
    }
    s/(\b'"$beginEsc"')\b.*\b('"$endEsc"'\b)/\1'"$replaceEsc"'\2/
}' input.file