7

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

Kenny Rasschaert
  • 8,925
  • 3
  • 41
  • 58
Darkmage
  • 323
  • 3
  • 12

4 Answers4

10

One line of sed can do this for you:

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

Kenny Rasschaert
  • 8,925
  • 3
  • 41
  • 58
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,788
  • 1
  • 10
  • 15
  • @Geoz grep -Po '1234.*9876' test | awk -F9876 '{ print $1 }' | awk -F1234 '{print $NF}' would be correct for his requirement – kaji Jan 30 '12 at 11:52
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
  • 35,688
  • 8
  • 69
  • 98
  • this would work if the file content is always the same. But you do not know the content of "keep me test" is always of the same length – Goez Jan 30 '12 at 11:38
  • @Goez: I said that this works for this example, and can customized according to the possible input templates. It is not clear from the question. Can you parse any text file without knowing its template(s)?? – Khaled Jan 30 '12 at 11:40
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.

user606723
  • 544
  • 1
  • 4
  • 10