tags:

views:

54

answers:

4

I've got a text file, and wish to extract every above the !--- comment ---! into a new file, not based line numbers (but checking for the comment), How would I do this?

test123
bob
ted
mouse
qwerty
!--- comment ---!
123456
098786
+1  A: 
sed -n '/^!--- comment ---!$/q;p' somefile.txt
Ignacio Vazquez-Abrams
+1  A: 

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

Jonathan Leffler
+2  A: 

Use sed, or a while loop:

while read line
do
    if [[ $line = '!--- comment ---!' ]];
    then
        break;
    else
        echo $line;
    fi;
done < input.txt > output.txt
martin clayton
A: 
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.

glenn jackman