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'

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

4 Comments

Can you elaborate a little bit? What does the 1 do at the end?
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.
I think that field separator is \t, not a simple space. So you should use -F option in this case.
@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.
0

This is an awk problem:

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

2 Comments

Old habbits... awk is rarely the only stream editor in the pipeline ;)
cat is rarely usefull even if you use multiple pipelines ;)
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; }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.