6

Yesterday a situation came up where someone needed me to separate out the tail end of a file, specified as being everything after a particular string (for sake of argument, "FOO"). I needed to do this immediately so went with the option that I knew would work and disregarded The Right Way or The Best Way, and went with the following:

grep -n FOO FILE.TXT | cut -f1 -d":" | xargs -I{} tail -n +{} FILE.TXT > NEWFILE.TXT

The thing that bugged me about this was the use of xargs for a singleton value. I thought that I could go flex my Google-Fu on this but was interested to see what sort of things people out in SO-land came up with for this situation

geoffjentry
  • 4,674
  • 3
  • 31
  • 37

3 Answers3

15
sed -n '/re/,$p' file

is what occurs to me right off.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • 2
    The right tool for the right job. `sed` is what you want. Mod +1. – David W. May 11 '11 at 19:25
  • 1
    (I guess where re means "regular expression") (i.e: sed -n '/search_pattern/,$p' file) – dajon Aug 09 '14 at 21:52
  • What if you want to replace `re` with a shell variable? For example, `foo="my pattern"; sed -n '/$foo/,$p' file` does not work because the `'` prevents shell expansion, and `sed -n "/$foo/,$p" file` does not work because the shell tries to expand `$p`, leading to error `sed: -e expression #1, char 27: unexpected `,'` – user5359531 Jun 26 '17 at 15:46
10

Did you consider just using grep's '--after-context' argument?

Something like, this should do the trick, with a sufficiently large number to tail out the end of the file:

grep --after-context=999999 -n FOO FILE.TXT > NEWFILE.TXT
Phil Street
  • 2,735
  • 2
  • 20
  • 25
  • Don't you need to supply a NUM argument to that? That was exactly the sort of functionality I was initially thinking of – geoffjentry May 11 '11 at 17:27
  • Ah, did you add that after initially posting? I didn't think to do an overly large number. As an aside 999999 might not have been enough in this case, but your point remains. – geoffjentry May 11 '11 at 17:31
  • Yes, sorry Geoff, you must have caught me in the middle of making the edit with the example. – Phil Street May 11 '11 at 17:31
  • 7
    If 999999 may not be sufficient, then `--after-context=$(wc -l < FILE.TXT)` will – glenn jackman May 11 '11 at 18:12
1

Similar to geekosaur's answer above, but this option excludes rather than includes the matched line:

sed '1,/regex/d' myfile

Found this one here after trying the option above.

John Rix
  • 6,271
  • 5
  • 40
  • 46