eplictical
eplictical

Reputation: 647

"Awk" to print from one token to next token OR end of file

To print from a line containing "hi" to a line containing "bye", I do:

awk '/hi/./bye/'

To print from a line containing "hi" to end of file, I do:

awk '/hi/,0'

How do I script to end printing at either of these end conditions?

Upvotes: 0

Views: 1572

Answers (3)

Chris Seymour
Chris Seymour

Reputation: 85845

In awk using a variable p as a flag:

$ cat file
start
line 2
hi
line 4
bye
end

$ awk '/hi/{p=1}{if (p) print}' file
hi
line 4
bye
end

$ awk '/hi/{p=1}{if (p) print}/bye/{p=0}' file
hi
line 4
bye

More concise:

$ awk '/hi/{p=1}p' file
hi
line 4
bye
end

$ awk '/hi/{p=1}p;/bye/{p=0}' file
hi
line 4
bye

I like sed for this however:

$ sed -n '/hi/,/bye/p' file
hi
line 4
bye

$ sed -n '/hi/,$p' file
hi
line 4
bye
end

Upvotes: 5

Ed Morton
Ed Morton

Reputation: 203985

awk '/hi/{f=1} f; /bye/{f=0}' file

If you ever want to print either or both of the delimiter lines, just re-order those 3 conditions.

Upvotes: 0

Kent
Kent

Reputation: 195169

I try to re-phase your question:

I want to print a file from line containing "hi", till line containing "bye", if there is no "bye" in file, I print from "hi" till EOF. (with awk)

if my understanding was correct,in fact you have given yourself answer:

awk '/hi/,/bye/'  

will do the job.

let's test with awk '/5/,/0/'

kent$  seq 12 |awk '/5/,/0/'
5
6
7
8
9
10

kent$  seq 9 |awk '/5/,/0/'                                                                                                                                                 
5
6
7
8
9

in the 2nd command, there is no 0 in the "file", so it will just print from /5/ till the end.

Note that in the "found" case, you have to handle "exit", otherwise if there were lines containing "hi" after "bye", they would be printed as well.

I hope this is what you were asking.

Upvotes: 2

Related Questions