awk + print lines from the first line until match word
Solution 1
Try:
$ awk '1;/PPP/{exit}' file
AAA
BBB
JJJ
OOO
345
211
BBB
OOO
OOO
PPP
Solution 2
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 ...
Solution 3
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
Related videos on Youtube
Comments
-
maihabunash over 1 year
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
-
Costas over 9 yearsSame with above via
sed
:sed '/PPP/q' infile
-
cuonglm over 9 years@Costas: Yes, the OP want
awk
, so I don't give others tools. -
cidermole over 8 yearsThe 1 at the beginning is like a full statement "// {print $0}" that is always matched. awk does not print without it.
-
cuonglm over 8 years@cidermole: Not exactly.
1
is like{print $0}
. Also note that//
is an empty pattern and the result is unspecified. It's work ingawk
,mawk
, Brian Kernighan own version but not innawk
,oawk
from heirloom tools chest. -
Gautama about 7 yearsThanks for the sed solution! I just want it done and I don't care about tool