如何在外壳中打印特定单词前面的字符串



我有一个字符串,我想打印所有以 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

使用 GNU sed :

$ sed -n 's/ echo/&n/g;:a;/echon/P;s/echon/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
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

脚本.awk

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

观察以下内容:

$ input='This is a echo test example echo please help me echo with this echo question'
$ grep -Po '.*?echo' <<< "$input"
This is a echo
 test example echo
 please help me echo
 with this echo

使用非贪婪的正则表达式匹配,我们得到一系列以 echo 结尾的行。

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

str=
while IFS= read -r line; do
    str+="$line"
    echo "$str"
done < <(grep -Po '.*?echo' <<< "$input")

导致

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

相关内容

  • 没有找到相关文章

最新更新