7

I want to print all lines from file until the match word please advice how to do that with awk

for example

I want to print all lines until word PPP

remark the first line chuld be diff from AAA ( any word )

cat file.txt

AAA   ( the first line/word chuld be any word !!!!! )
BBB
JJJ
OOO
345
211
BBB
OOO
OOO
PPP
MMM
(((
&&&

so I need to get this

AAA
BBB
JJJ
OOO
345
211
BBB
OOO
OOO
PPP

other example ( want to print until KJGFGHJ )

 cat file.txt1

 HG
 KJGFGHJ
 KKKK

so I need to get

 HG
 KJGFGHJ
12

Try:

$ awk '1;/PPP/{exit}' file
AAA
BBB
JJJ
OOO
345
211
BBB
OOO
OOO
PPP
  • 5
    Same with above via sed : sed '/PPP/q' infile – Costas Nov 30 '14 at 11:37
  • @Costas: Yes, the OP want awk, so I don't give others tools. – cuonglm Nov 30 '14 at 11:38
  • The 1 at the beginning is like a full statement "// {print $0}" that is always matched. awk does not print without it. – cidermole Oct 21 '15 at 9:03
  • @cidermole: Not exactly. 1 is like {print $0}. Also note that // is an empty pattern and the result is unspecified. It's work in gawk, mawk, Brian Kernighan own version but not in nawk, oawk from heirloom tools chest. – cuonglm Oct 21 '15 at 9:45
  • Thanks for the sed solution! I just want it done and I don't care about tool – Aaron McMillin Mar 10 '17 at 19:15
5

Alternatively use a range pattern matching the first line (NR equal to 1) until the first match of 'PPP' in a line

awk 'NR==1,/PPP/' file

if the line must exactly match 'PPP' only use

awk 'NR==1,/^PPP$/' file

If you would like to do the same for each file in the argument list, use the FNR variable which resets to 1 for the first line of each processed file

awk 'FNR==1,/PPP/' file1 file2 ...
1

As OP said his first line or word of file can be contains any word(like PPP itself), so you need to check that and scape the first line from matching and avoid the awk to exit there.

Then you can try this:

Input file:

PPP # the first line/word chuld be any word !!!!! )
BBB
$$$
JJJ
OOO
PPP
345
PPP
%%%

Command:

awk '1;/PPP/{if (NR>1) exit}' file

Output:

PPP # the first line/word chuld be any word !!!!! )
BBB
$$$
JJJ
OOO
PPP

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.