使用shell工具提取文件的一部分

时间:2010-05-24 23:11:07

标签: bash shell

我有一个文本文件,并希望提取上面的每一行!---评论---!到新文件,不是基于行号(但检查注释)。我该怎么做?

test123
bob
ted
mouse
qwerty
!--- comment ---!
123456
098786

4 个答案:

答案 0 :(得分:1)

sed -n '/^!--- comment ---!$/q;p' somefile.txt

答案 1 :(得分:1)

对于文件,你的sed程序是否提前停止并不重要;对于管道输入,如果你提早停止,一些程序会感到不安。对于那些,您应该从评论中删除:

sed '/^!--- comment ---!$/,$d' somefile.txt

如果你真的必须使用bash而不是shell工具,比如sed,那么:

x=1
while read line
do
    if [ "$line" = "!--- comment ---!" ]
    then x=0    # Or break
    elif [ $x = 1 ]
    then echo "$line"
    fi
done < somefile.txt

该代码也可以与Bourne和Korn shell一起使用,我希望它几乎可以与任何基于Bourne shell(任何符合POSIX标准的shell)的遗产一起使用。

答案 2 :(得分:1)

使用sed或while loop

while read line
do
    if [[ $line = '!--- comment ---!' ]];
    then
        break;
    else
        echo $line;
    fi;
done < input.txt > output.txt

答案 3 :(得分:0)

awk '/!--- comment ---!/ {exit} 1' somefile.txt

如果评论是可变的:

awk -v comment="$comment_goes_here" '$0 ~ comment {exit} 1' somefile.txt

尾随1指示awk只为所有未匹配的行使用默认操作(print)。