Shell Scripting删除字符串前后的文本

时间:2011-03-01 18:14:49

标签: shell scripting sed awk

我需要shell脚本一种方法来从文本文件中获取随机未知​​的垃圾文本。我被困在如何做到这一点,因为我不知道垃圾文本会说什么。基本上我需要删除之前,之后和之间的所有内容。我想保留文章里面的文字。

--Begin file


random unknown junk text

----Begin Piece one ---- 
random important text
----End Piece one ----

random unknown junk text

----Begin Piece two ---- 
random important text
----End Piece two ----

random unknown junk text

----Begin Piece two ---- 
random important text
----End Piece two ----

random unknown junk text


end of file

2 个答案:

答案 0 :(得分:2)

sed -n '/^\(--Begin file\|end of file\)/{p;b}; /^----Begin Piece/{p;:a;n;/^----End Piece/{p;b};p;ba}' inputfile

说明:

  • /^\(--Begin file\|end of file\)/{p;b} - 打印文件开头/结尾行(与文字文本匹配)
  • /^----Begin Piece/{ - 如果该行与块开始标记匹配
    • p - 打印
    • :a - 标记
    • n - 阅读下一行
    • /^----End Piece/{ - 如果是块结束标记
      • p - 打印
      • b - 分支到最后阅读下一行输入
    • } - 结束如果
    • p - 打印区块内的一行
    • ba - 分支以标记a以查看块中是否有更多行
  • } - 结束如果

答案 1 :(得分:0)

#!/bin/bash
exec 3< file.txt
fl=0
regex='----Begin Piece.+'
regexe='----End Piece.+'
while read <&3
do
    if [ $fl -eq 1 ] && [[ ! "$REPLY" =~ $regexe ]]; then
        echo "$REPLY"
    fi
    if [[ "$REPLY" =~ $regex ]]; then fl=1; fi
    if [[ "$REPLY" =~ $regexe ]]; then fl=0; fi
done
exec 3>&-