tulamba
tulamba

Reputation: 131

Match only very first occurrence of a pettern using awk

I am trying to follow the solution at

Moving matching lines in a text file using sed

The situation is that pattern2 needs to be applied just once in the whole file. How can I change the following to get this done

awk '/pattern1/ {t[1]=$0;next}
     /pattern2/ {t[2]=$0;next}
     /pattern3/ {t[3]=$0;next}
     /target3/ { print t[3] }
     1
     /target1/ { print t[1] }
     /target2/ { print t[2] }' file

Here is the file on which I applied the pattern2 (RELOC_DIR)

asdasd0
-SRC_OUT_DIR = /a/b/c/d/e/f/g/h
RELOC_DIR = /i/j/k/l/m
asdasd3
asdasd4
DEFAULTS {
asdasd6
$(RELOC_DIR)/some other text1
$(RELOC_DIR)/some other text2
$(RELOC_DIR)/some other text3
$(RELOC_DIR)/some other text4

and the last 4 lines of the file got deleted because of the match.

asdasd0
-SRC_OUT_DIR = /a/b/c/d/e/f/g/h
asdasd3
asdasd4
DEFAULTS {
RELOC_DIR = /i/j/k/l/m
asdasd6

Upvotes: 0

Views: 1682

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133518

I am assuming you need to check pattern2 along with some other condition if this is the case then try.

awk '/pattern1/ {t[1]=$0;next}
     /pattern2/ && /check_other_text_in_current_line/{t[2]=$0;next}
     /pattern3/ {t[3]=$0;next}
     /target3/ { print t[3] }
     1
     /target1/ { print t[1] }
     /target2/ { print t[2] }' file

Above is checking check_other_text_in_current_line string(which is a sample and you could change it as per your actual string) is present along with pattern2 also in same line. If this si not what you are looking for then please post samples of input and expected output in your post.



OR in case you are looking that only 1st match for pattern2 in Input_file and skip all others then try. It will only print very first match for pattern2 and skip all others.(since samples are not provied by OP so this code is written only for the ask of specific pattern matching)

awk '/pattern1/ {t[1]=$0;next}
     /pattern2/ && ++count==1{t[2]=$0;next}
     /pattern3/ {t[3]=$0;next}
     /target3/ { print t[3] }
     1
     /target1/ { print t[1] }
     /target2/ { print t[2] }' file

OR

awk '/pattern1/ {t[1]=$0;next}
     /pattern2/ && !found2{t[2]=$0;found2=1;next}
     /pattern3/ {t[3]=$0;next}
     /target3/ { print t[3] }
     1
     /target1/ { print t[1] }
     /target2/ { print t[2] }' file


EDIT: Though my 2nd solution looks like should be the one as per OP's ask but complete picture of requirement is not given so adding code only for printing Pattern2(string RELOC_DIR)'s first occurence here.

awk '/RELOC_DIR/ && ++ count==1{print}'  Input_file
RELOC_DIR = /i/j/k/l/m

OR

awk '!found2 && /RELOC_DIR/ { t[2]=$0; found2=1; print}' Input_file

Upvotes: 2

Related Questions