Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 10 down vote accepted

One line of sed can do this for you:

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

share|improve this answer
thanks very helpful – Darkmage Jan 30 '12 at 14:03

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

share|improve this answer
@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

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

share|improve this answer
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

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.