0

I have a file (xyz.dat) that contains all kinds of random statements. What I need to do is to search this file for VALUE1 on a line and only print to file when VALUE1 is immediately followed on a new line by VALUE2.

Example input:

1 VALUE1
2 VALUE1
3 VALUE1
4 VALUE2
5 VALUE1
6 VALUE2
7 VALUE2

Expected output:

3 VALUE1
4 VALUE2
5 VALUE1
6 VALUE2
1

Simple sed approach:

sed -n '/ VALUE1$/{ N; / VALUE2$/p }' xyz.dat > new.txt

new.txt contents:

3 VALUE1
4 VALUE2
5 VALUE1
6 VALUE2
  • 1
    If there is another VALUE1 between 3 and 4, you don't catch it – ctac_ May 24 '18 at 17:35
1

With sed

sed '/ VALUE1$/!d;N;/ VALUE2$/b;D' infile
0

Another awk approach:

awk '/VALUE1/{ bkup=$0 } /VALUE2/ && bkup{print bkup ORS $0; bkup=""}' infile
  • Won't this print VALUE2 lines even if not preceeded with VALUE1? – DopeGhoti May 24 '18 at 16:28
  • @DopeGhoti No, there is bkup flag controlling that. – αғsнιη May 24 '18 at 16:31
0

Two Awk solutions:

-- based on getline function:

awk '/ VALUE1$/ && (getline nl) > 0 && nl ~ /VALUE2$/{ print $0 ORS nl }' xyz.dat

-- based on record number comparison:

awk '/ VALUE1$/{ rec = $0; rn = NR+1 }NR == rn && /VALUE2$/{ print rec ORS $0 }' xyz.dat

The output (for both):

3 VALUE1
4 VALUE2
5 VALUE1
6 VALUE2
  • Wow thanks so much. This did not work on my 35MB data fie (xyz.dat). However, I created a dummy file (dummy.dat) which looks like this: – SSDdude May 25 '18 at 16:03
  • <PLEASE IGNORE PREVOUS COMMENT> Hey Roman... wow thanks so much. I think I am running into some thing strange! This did not work on my 35MB data fie (xyz.dat). However, I created a 100 line dummy file (dummy.dat) including random lines of "VALUE1", "VALUE2", "GARBAGE" and it works FLAWLESSLY! GARBAGE is omitted and only VALUE1 succeeded by VALUE2 are printed perfectly staggered! I am confused here but thinking it might have something to do with the size of the file... Any ideas here? THANKS ALL! – SSDdude May 25 '18 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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