newmusicblog
newmusicblog

Reputation: 127

Bash script to remove all lines in a text file untill a string

I have a file with lots of words like:

one
two
three
four
tree
house
cat
dog
etc

and I want to remove all words until "house" in such a way to get only:

cat
dog
etc

Upvotes: 2

Views: 1340

Answers (4)

yabt
yabt

Reputation: 1

You may also use the Unix text editor ed for this kind of task. Note that ed reads the entire file into memory and edits files in-place without previous backup though.

# prints result to stdout
printf '%s\n' H ',g/^house$/1,/^house$/d' ',p' | ed -s file
printf '%s\n' H ',g/^house$/1,//d' ',p' | ed -s file  # short version

# edits file in-place
printf '%s\n' H ',g/^house$/1,/^house$/d' wq | ed -s file

For more information on ed please see:

"Editing files with the ed text editor from scripts",

http://wiki.bash-hackers.org/howto/edit-ed

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363607

awk '
    BEGIN                  { noprint = 1; cue = ARGV[1]; ARGV[1] = ""}
    (!noprint)             { print }
    (noprint && $0 == cue) { noprint = 0 }
' house textfile

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

sed -n '0,/^house$/d;p' input.txt

Upvotes: 6

Simon Whitaker
Simon Whitaker

Reputation: 20566

You can do this easily with a Perl one-liner, which you can of course incorporate into a bash script.

$ perl -ne 'print if $ok; $ok=1 if /^house$/' sample.txt 
cat
dog
etc

Upvotes: 0

Related Questions