如何打印shell中特定单词之前的字符串?

时间:2016-06-04 06:45:22

标签: string bash shell

我有一个字符串,我想打印所有以shell中的特定单词结尾的子字符串,例如

This is a echo test example echo please help me echo with this echo question

我希望它的输出为

This is a echo
This is a echo test example echo
This is a echo test example echo please help me echo
This is a echo test example echo please help me echo with this echo

3 个答案:

答案 0 :(得分:1)

使用GNU sed:

$ sed -n 's/ echo/&\n/g;:a;/echo\n/P;s/echo\n/echo/;ta' file
This is a echo
This is a echo test example echo
This is a echo test example echo please help me echo
This is a echo test example echo please help me echo with this echo

答案 1 :(得分:0)

awk -vword="echo" '{var="";for(i=1;i<=NF;i++){var=var$i""FS;if(index($i,word) > 0){print var"\n"}}}' < file

通过awk脚本文件

awk -vword="echo" -f script.awk  < file

<强> script.awk

#! /bin/awk -f
{
    var="";
    for(i=1;i<=NF;i++){
        var=var$i""FS;
        if(index($i,word) > 0){
            print var"\n"
        }
    }
}

答案 2 :(得分:0)

请注意以下事项:

echo

使用非贪婪的正则表达式匹配,我们得到一系列以str= while IFS= read -r line; do str+="$line" echo "$str" done < <(grep -Po '.*?echo' <<< "$input") 结尾的行。

我们使用此命令作为shell循环的输入,我们在其中重新组合原始句子并在每行之后打印当前状态:

This is a echo
This is a echo test example echo
This is a echo test example echo please help me echo
This is a echo test example echo please help me echo with this echo

导致

{{1}}