Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am having a file whose contents are as follows:

A,10,20,30,40,50
B,20,40,10,30,60
C,30,50,20,40,10
D,40,50,20,10,30

I wish to perform some arithmetic operation (say Division by 10) on a particular column (say Column 3) of above CSV file. So that, it reads :

A,10,2,30,40,50
B,20,4,10,30,60
C,30,5,20,40,10
D,40,5,20,10,30

How can this be done?

share|improve this question
    
If your file is really this simple, you already seem to have the answer. If your CSV file is more complex (e.g. with values quoted and spanning multiple lines), parsing using bash is going to be fragile at best. CSV parsing is best done with some specialised package for Perl or Python to prevent problems with real CSV files. –  Anthon Apr 22 at 6:45

2 Answers 2

up vote 3 down vote accepted

Try this:

% awk -F',' '$3/=10' OFS=',' file
A,10,2,30,40,50
B,20,4,10,30,60
C,30,5,20,40,10
D,40,5,20,10,30
share|improve this answer
    
I think you missed that the author wants a solution using bash, not awk. –  Anthon Apr 22 at 6:47
    
@Anthon I doubt that there is casual (non exotic hardware) situation where environment has full bash (not sh) implementation and is limited not to use awk. –  IBr Apr 22 at 6:59
    
@Anthon Well, that is what the asker asked litterally , but not what he wanted, considering the answer is accepted. –  Bernhard Apr 22 at 12:34
    
@Bernhard There have been multiple questions on U&L where the OP would comment on such an answer with something like: what part of "in bash" do you not understand. I just tried to warn the answerer, who might have misread the question. –  Anthon Apr 22 at 13:44

If you really want to do it in bash, you can:

$ while IFS="," read a b c rest; do 
    printf "%s,%s,%s,%s\n" $a $b $((c/10)) $rest; 
  done < file.csv 
A,10,2,30,40,50
B,20,4,10,30,60
C,30,5,20,40,10
D,40,5,20,10,30

While this works for simple integer arithmetic, bash cannot deal with floating point numbers so if you were to try an arithmetic operation that produced non-integers it would fail. Horribly. Bash is really not the best tool for the job here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.