开发者

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


Use sed, or a while loop:

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


For files, it doesn't matter if your sed program stops early; 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:

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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜