file:
string1 string2 string3 string4 string5 string6
string3 string1 string2 string4 string5 string6
string6 string3 string2 string4 string1 string5
expectation:
string2 string3 string4 string5
string2 string4 string5
string2 string4 string1 string5
Match pattern=string1
How to print match lines but only from string2
to string5
with awk
?
Unfortunately this is not processing in line :
awk '/string2/,/string5/' file
Let's assume there are few long lines with string2
and string5
in different places.
You can use awk's
index
andmatch
functions e.g.Ex.
Note this assumes that
string2
will exist in every line in whichstring5
exists - if that's not the case, you will need to check the value ofindex($0,"string2")
and act accordingly.Effectively,what you want to do is iterate over each field, and "enable" printing with a variable if result is found. Thus, what you need is a flag variable and for loop:
What happens here is that the whole code block will run for each line. On each line we are iterating from first field to last. Initially we set flag variable to 0, then proceed to examine each field. If field contains the desired "string2" , the flag will be set to 1, and if it is "string6" (which is the one when we want to stop) - flag will be set to 0; finally, if statement will check if flag is set and print the current field appended with field separator (represented by FS variable). After all has been printed we also insert new-line via
print ""
command.In case where you have lines without match, the above command will print blank lines. You can mitigate that via adding search pattern, which will limit code-block execution only when there is pattern found in string:
Alternatively, we can use an extra variable with same result:
First, you only keep lines containing
string2
andstring5
in that particular order (pattern in line 1). All you have to do next is strip everything beforestring2
and everything afterstring5
(lines 2 and 3) and finally print what remains.Using grep: