1

I would like to zero one column of a csv file. Let's assume the csv file looks like this:

col1|col2|col3
v   |  54| t
a   |  25| f
d   |  53| f
s   |  04| t

Using awk this way, gives me almost what I want

command:

awk -F'|' -v OFS='|'  '$2=0.0;7' input.csv > output.csv

the result

col1|0|col3
v   |0| t
a   |0| f
d   |0| f
s   |0| t

But notice that the column header has been also zeroed which is something I am trying to avoid. So I tried to skip the first line with the awk command but I am getting an empty file

awk -F'|' -v OFS='|'  'NR<1 {exit} {$5=0.0;7}' input.csv > output.csv

What am I missing?

2
  • why do you have a seven there? seems like a typo... Commented Jul 9, 2015 at 9:38
  • @Ismael check the comment of user112638726 in the accepted answer. Commented Jul 9, 2015 at 9:47

2 Answers 2

6

Just apply the rule from the 2nd line on with a NR>1 {}:

$ awk -F'|' -v OFS='|'  'NR>1{$2=0.0}7' file
col1|col2|col3
v   |0| t
a   |0| f
d   |0| f
s   |0| t

Why wasn't your approach awk -F'|' -v OFS='|' 'NR<1 {exit} {$5=0.0;7}'working?

The expression NR<1{exit} is never True because NR is always at least 1.

This means that the second expression {$5=0.0;7} is always evaluated. The $5=0.0 is fine, but 7 is not printing as you would want to, because to print a line you need some kind of print instruction. It would work if you moved the 7 outside the braces, so that it will evaluate to True and the record will be printed: awk -F'|' -v OFS='|' 'NR<1 {exit} {$5=0.0}7'.

But this wouldn't do what you want. Instead, you may want to say NR==1 {next} to skip the first line. However, this will prevent it from being printed:

$ awk -F'|' -v OFS='|'  'NR==1{next} $2=0.0;7' file
v   |0| t
a   |0| f
d   |0| f
s   |0| t
Sign up to request clarification or add additional context in comments.

3 Comments

This is the right answer to resolve my issue, thanks. I will accept it when I can.
@MedAli You also seem to not quite understand what 7 does in this context. As it is non zero it is seen as awk as true. The same goes for $2=0.0 but it is seen as false. So technically your first command(in the question) is seen as '$2=0.0{print $0};7{print $0}' or 'false{print $0};true{print $0}.
@User112638726, thank you. Now I do understand what 7 stands for :)
2

Change exit to next to skip the remaining actions for that first line.

1 Comment

I did that, but the resulting file is empty

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.