2

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'

KyleMit
  • 30,350
  • 66
  • 462
  • 664
DEVANG PANDEY
  • 157
  • 2
  • 15

4 Answers4

6
$ 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
jlliagre
  • 29,783
  • 6
  • 61
  • 72
  • 1
    Can you elaborate a little bit? What does the `1` do at the end? – pfnuesel Nov 27 '13 at 13:00
  • It's a cryptic way to display the current line. I really should have put `{print}` instead for readability but was trying to get as concise as possible. – jlliagre Nov 27 '13 at 13:04
  • I think that field separator is \t, not a simple space. So you should use -F option in this case. – Idriss Neumann Nov 27 '13 at 13:06
  • 1
    @IdrissNeumann Hello Idriss ! That's not necessary unless spaces do appear in column values which is not the case with the data posted. Awk by default consider both spaces and tabs as field separators. – jlliagre Nov 27 '13 at 13:14
0

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
# ...
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
0

This is an awk problem:

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

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; }
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820