6

If I have a log file and want to dump only the text between 1234 and 9876 in to another file, how can i do this easily?

If I have a text file like this:

idsfsvcvs sdf sdf e e  sd vs d s g sg  s vc  d

slkdfnls 1234 keep me text 9876 das a g w eg dsf sd fsdf
sdfs fs dfsdf
sdfsdf sdf
sdf s fs
dfsf ds

I want to do somthing like this

$ getinfo "1234" "9876" log

$ cat log

keep me text

Darkmage
  • 313

4 Answers4

10

One line of sed can do this for you:

sed -n 's/.*1234 \(.*\)9876.*/\1/p' textfile.txt > log

2

normally you can do this with grep and the -o param.

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. 

so it would be something like:

 grep -Po '1234.*9876' >> log

Not 100% sure about the regex btw, I did not test it

Goez
  • 1,858
1

This depends on your file content. You can start by something simple like:

$ grep 1234 logfile | grep 9876 | cut -d ' ' -f 3,4,5

This works for the provided example. You can work on it to cover other data formats if needed. You can also redirect the output to a file by appending > /path/to/output

Khaled
  • 37,789
0

For what it's worth, I would do the following:

  1. grep 1234.*9876 > myfile
  2. vim myfile
  3. :%s/^.*1234// (delete everything up to 1234)
  4. :%s/9876.*$// (delete everything after and including 9876)

Not perfect, or the best way, but easy to remember if you often use vim.