Shell /awk script for Percentage

having two columns, A and B.. i need to add another column C in a file and calculate the percentage based on the column A and B. (COLUMN B/ COLUMN A *100) . "|" is delimiter separating the A and B.. need C column with the percentage value. Thanks for your help

100|50   |50%          (50)/100*100 )
200|200  |100%

Please show us a sample input file, the corresponding output file you are hoping to produce, and whatever awk code you have tried to use to solve this problem on your own.

I don't understand what the 4th and 5th fields in the first line of your desired output are supposed to be (nor why having mismatched parentheses in your output is desirable)???

Are the <space>s at the end of field 2 in your output present in your input file? If not, why are they present in your output file? Is your output field separator just a vertical bar character ( | ) or is there some reason why field 2 and field 3 in your output are separated by a variable number of <space>s and a vertical bar character? And, why are the 4th and 5th fields separated by varying numbers of <space>s instead of by vertical bar characters?

Thanks Don,

Input having only 2 columns A and B

A|B
100|50  
200|200

Third column has to be generated with %Percentage ( B/A*100)

Like below -

A|B|C
100|50|50%
200|200|100%

Hello kartikirans,

Could you please try following and let me know if this helps you.

awk 'BEGIN{FS=OFS="|"}FNR==1{print $0,"C";next} {sub(/ +$/,"");$(NF+1)=($2/$1)*100} 1'  Input_file

Thanks,
R. Singh

Thanks Singh, command looks good for me. If there are strings in between , can we ignore this and add as NA

A|B
100|50 
200|200
DDD|DDD

Expected-

A|B|C
100|50|50%
200|200|100%
DDD|DDD|NA

Maybe something like:

awk '
BEGIN {	FS = OFS = "|"
}
NR == 1 {
	print $0, "C"
	next
}
{	gsub(/ /, "")
	if($1 $2 ~ /[^0-9]/)
		$3 = "NA"
	else	$3 = $2 / $1 * 100 "%"
}
1' file

will give you what you want? (Note that this assumes that all <space>s in fields 1 and 2 should be deleted, while the code Ravinder suggested only deletes trailing <space>s in those two fields.)

Hello kartikirans,

Could you please try following and let me know if this helps you.

awk 'BEGIN{FS=OFS="|"}FNR==1{print $0,"C";next} {sub(/ +$/,"");$(NF+1)=$1~/[0-9/+/||$2~/[0-9]+/?($2/$1)*100"%":"NA"} 1'  Input_file

Thanks,
R. Singh