Issue
i have different lines in one file .I want to achieve the output as below. I want to print the next word after aaaa and test words with delimiter ,.
Input is
Line Aaaa orange test match
Colour Aaaa banana test sun
Ball Aaaa guava test Saturday
Basket Aaaa tomato test sunset
Output has to be
Orange ,match
Banana ,sun
Guava, Saturday
Tomato,sunset
Could anyone please help on this
I have tried using sed ,grep commands but i didnt get the expected output
Solution
awk
solution
Assuming you want to ignore lines where "Aaaa" does not occur, the following awk
process should achieve your needs (if the relative positions of"Aaaa" and "test" are constant - see edit below):
awk '{for(i=1;i<NF;i++) if ($i=="Aaaa") {print $(i+1) ", " $(i+3); next}}' file
explanation
Each line of file
is processed (by default) as white-space separated fields. A loop examines each field for the required pattern
("Aaaa") and (if found) prints the values of the next field, the required comma, and the value of the final required field.
Edit
For cases where the position of "test" may also vary, providing "test" is never before "Aaaa"*, the following procedure should work:
awk '{for(i=1;i<NF;i++) {if ($i=="Aaaa") {line= $(i+1) ", "; } if ($i=="test") {line=line $(i+1); print line;next}}}' file
It will need reworking if "test" can come before "Aaaa" as follows:
awk '{partA=partB=""; for(i=1;i<NF;i++) {if($i=="Aaaa") partA=$(i+1); if($i=="test") partB=$(i+1); if(partB && partA) {print partA ", " partB; next}}}' file
This version requires both "Aaaa" and "test" are present but they can be in any order on the line.
(each) tested on file
:
Line Aaaa orange test match
Colour Aaaa banana test sun
Ball Aaaa guava test Saturday
Basket Aaaa tomato test sunset
output (for all three versions)
orange, match
banana, sun
guava, Saturday
tomato, sunset
(using GNU Awk 5.1.0)
Answered By - Dave Pritlove Answer Checked By - Willingham (WPSolving Volunteer)