简体   繁体   English

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

[英]Using shell tools to extract part of a file

I've got a text file, and wish to extract every line above the !--- comment ---! 我有一个文本文件,并希望提取上面的每一行!---评论---! into a new file, not based on line numbers (but checking for the comment). 到新文件,不是基于行号(但检查注释)。 How would I do this? 我该怎么做?

test123
bob
ted
mouse
qwerty
!--- comment ---!
123456
098786
sed -n '/^!--- comment ---!$/q;p' somefile.txt

For files, it doesn't matter if your sed program stops early; 对于文件,如果你的sed程序提前停止并不重要; for piped input, some programs get upset if you stop early. 对于管道输入,如果你提早停止,一些程序会感到不安。 For those, you should delete from the comment onwards: 对于那些,您应该从评论中删除:

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

If you really must use bash rather than shell tools such as sed, then: 如果你真的必须使用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

That code will also work with the Bourne and Korn shells, and I would expect it to work with almost any shell with a heritage based on the Bourne shell (any POSIX-compliant shell, for example). 该代码也可以与Bourne和Korn shell一起使用,我希望它可以与几乎任何具有基于Bourne shell(任何符合POSIX标准的shell)的遗产的shell一起使用。

Use sed, or a while loop : 使用sed或while循环

while read line
do
    if [[ $line = '!--- comment ---!' ]];
    then
        break;
    else
        echo $line;
    fi;
done < input.txt > output.txt
awk '/!--- comment ---!/ {exit} 1' somefile.txt

If the comment is variable: 如果评论是可变的:

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

The trailing 1 instructs awk to simply use the default action (print) for all lines not otherwise matched. 尾部1指示awk简单地对所有未匹配的行使用默认动作(print)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM