DEVANG PANDEY
DEVANG PANDEY

Reputation: 157

bash working on multiple columns in same file

I am facing a problem in comparing two columns of same file and then replacing value of one column on basis of another one

For example, my file is like :

name col1  col2
abc  no    no
xyz  yes   yes
man  no    no
wrr  no    no

Here I want to check that for every 'no' value in col1 of file I want to change value of col2 as 'N/A'

Upvotes: 2

Views: 590

Answers (4)

Idriss Neumann
Idriss Neumann

Reputation: 3838

Using sed :

[ ~]$ sed "s/\([A-Za-z]*\ *no\ *\).*/\1N\/A/g" file
name col1  col2
abc  no    N/A
xyz  yes   yes
man  no    N/A
wrr  no    N/A

Using awk :

[ ~]$ awk '$2 == "no" {$3="N/A"} {print}' file
name col1  col2
abc no N/A
xyz  yes   yes
man no N/A
wrr no N/A

You could also change your display as you want :

[ ~]$ awk '$2 == "no" {$3="N/A"} {print $1"\t"$2"\t"$3}' file
[ ~]$ awk '$2 == "no" {$3="N/A"} {print $1" "$2" "$3}' file
# ...

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328870

Here is a simple solution:

while read name col1 col2 ; do
   if[[ "$col" = no ]]; then
      echo "$name $col1 N/A"
   else
      echo "$name $col1 $col2"
   fi
done < file

If you need it faster, use this awk script:

$1 == "no" { print $1" "$2" N/A"; next; }
{ print; }

Upvotes: 0

smassey
smassey

Reputation: 5931

This is an awk problem:

cat your-file.txt | awk '{if ( $2 == "no" ) { $3 = "N/A"; } print $0 }' > your-new-file.txt

Upvotes: 0

jlliagre
jlliagre

Reputation: 30873

$ awk '$2=="no"{$3="N/A"}1' file
name col1  col2
abc no N/A
xyz  yes   yes
man no N/A
wrr no N/A

Upvotes: 6

Related Questions