Need to search for A in the file and whichever location is A is located need to get its next column i.e need to get 45 78 and 98 and put these values at end of file as new column
Output
U A 45 B 45
N A 78 M 78
M A 98 O 98
I can do this via a while loop and all the clutter in shell script but i need a efficient and clean way to achieve this
The awk script searches the pattern "A" in every line, then:
for(i=1;i<=NF;++i)--> The "for loop" goes through all the columns/fields (NF=last column number, in this case NF=4) for every line.
if($i=="A") --> Within the "for loop" is present the condition that says, when I pass for column i, and is found that column i has
a value ="A" ($i="A"),
print $0,$(i+1) --> then, inmediately print the whole line ($0), followed by an space "," and the value after column i =$(i+1)
If you want to know the column number in which match was found, simply remove the "$" symbol from
$i and you will have it, something like:
awk '{for(i=1;i<=NF;++i)if($i=="A")print "string A, was found in column " i}' inputfile
$i=Gives the content/value of the column, ($3= Content of column 3=45 or 78 or 98, depends line number);
i = Gives the number of the column, (3=Number of column 3=3).
Something which i tried but didn't worked need to get put a another text value if there is no match
If file has no Butten that row should have a some extra text "ABC" at end of column i tried putting a else clause but it seems like its duplicating the lines for which i need a flag variable which would check whether it has reached the end or not but how to put that flag ?
U A 45 B 45
N A 78 M 78
M A 98 O 98
M N 98 O ABC