Get Column location Dynamically

File Format

U	A	45	B
N	A	78	M	
M 	A	98	O

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

awk '{if($2=="A")print $1" " $2" " $3" " $4" " $3;else print $1" " $2" " $3" " $4}' filename

Hi dinjo_jo,

The sample has tab as field separator, the try:

awk '{for(i=1;i<=NF;++i)if($i=="A")print $0"\t"$(i+1)}' inputfile
U    A    45    B    45
N    A    78    M    78
M    A    98    O    98

If it has space as field separator remove the "\t" and use:

awk '{for(i=1;i<=NF;++i)if($i=="A")print $0,$(i+1)}' inputfile

Best regards.

How about this?

awk '{sub($0,$0 FS $3)}1' file

cgkmal it works.

How do i identify at which column the match was found ? So that i can do some more processing

awk '{for(i=1;i<=NF;++i)if($i=="A")print $0,$(i+1)}' inputfile

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).

Hope it helps,

Best regards

Very well explained , top notch

1 Like
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