Manipulating column in a file in UNIX

Hi

I have a file content.txt where I want to replace the value of second column of the file with half of the value of that column.
I only have to replace if the second column starts with COM_, rest all values have to be same
eg,

cat content.txt

|COM_A|123|JHV|8475
|ABC|2765|BV|876
|COM_B|2437|HDD|854
|YUT_F|78|JDHF|UE
|COM_GTH|8475|FNV|58

Output file

|COM_A|61.5|JHV|8475
|ABC|2765|BV|876
|COM_B|1218.5|HDD|854
|YUT_F|78|JDHF|UE
|COM_GTH|4237.5|FNV|58

Can you please let me know how to do it

Try:

awk '$2~/^COM_/{$3/=2}1' FS=\| OFS=\| file

To get a little practice myself....

OLD_IFS="$IFS"
IFS="|"
while read ColA ColB ColC ColD;do
    newB=$(echo "$ColB / 2" | bc)
    printf "$IFS$ColA$IFS$newB$IFS$ColC$IFS$ColD"
done
IFS="$OLD_IFS"

Hope this helps

@sea: IFS can be used local to the read command:

while IFS=\| read ColA ColB ColC ColD
do
  ...
done < file

So IFS does not need to be set and reset..
Note that ColA is empty, ColD contains both columns 4 and 5 and ColC needs to be changed if ColB meets the criteria..

1 Like
 awk -F "|" '/COM_/{$3=$3 / 2;}1' OFS="|" filename

Thanks Scrutinizer , the code worked well,

1 more question, is it possible to add one more level of validation,
like currently the code is working if the second column startes with _COM
I want to add one more level as the third column should only be "Scen"

Can you please let me know how can this be done

Like so, you mean?

awk '$2~/^COM_/ && $4=="Scen" {$3/=2}1' FS=\| OFS=\| file

Thanks all for the help