modify value's in CSV with bash-script
Asked Answered
A

4

5

I've the following CSV file's:

2012-07-12 15:30:09; 353.2
2012-07-12 15:45:08; 347.4
2012-07-12 16:00:08; 197.6
2012-07-12 16:15:08; 308.2
2012-07-12 16:30:09; 352.6

What I want to do is modify the value in the 2nd column...

What I already can do is extract the value and modify it this way:

#!/bin/bash
cut -d ";" -f2 $1 > .tmp.csv
for num in $(cat .tmp.csv)
    do
        (echo "scale=2;$num/5" | bc -l >> .tmp2.csv)
done
rm .tmp.csv
rm .tmp2.csv

But I need to have column1 in that file too...

I hope one of you can give me a hint, I'm just stuck!

Autopilot answered 17/7, 2012 at 12:47 Comment(4)
I spent too much time trying to do things like this. If you have python on your system I suggest you try that instead.Schoolfellow
I've absolutly no py experience, but might be able to work it out with a similar example...Autopilot
It'll probably be easiest to use awk, but you'll need to be more specific on what you want to do.Landward
Hi Kevin, I'll divide the value in the 2nd column through 5 and write it back to the csvAutopilot
B
4

From your code, this is what I understood

Input

2012-07-12 15:30:09; 353.2 
2012-07-12 15:45:08; 347.4 
2012-07-12 16:00:08; 197.6 
2012-07-12 16:15:08; 308.2 
2012-07-12 16:30:09; 352.6 

Awk code

awk -F ";" '{print $1 ";" $2/5}' input

Output

2012-07-12 15:30:09;70.64
2012-07-12 15:45:08;69.48
2012-07-12 16:00:08;39.52
2012-07-12 16:15:08;61.64
2012-07-12 16:30:09;70.52
Bluebell answered 17/7, 2012 at 13:9 Comment(0)
E
3

One way, using awk:

awk '{ $NF = $NF/5 }1' file.txt

Results:

2012-07-12 15:30:09; 70.64
2012-07-12 15:45:08; 69.48
2012-07-12 16:00:08; 39.52
2012-07-12 16:15:08; 61.64
2012-07-12 16:30:09; 70.52

HTH

Endsley answered 17/7, 2012 at 13:10 Comment(0)
S
3

Here's an almost-pure bash solution, without temp files:

#!/bin/bash

while IFS=$';' read col1 col2; do
    echo "$col1; $(echo "scale=2;$col2/5" | bc -l)"
done
Spit answered 17/7, 2012 at 13:30 Comment(0)
P
2

Try with awk:

awk '
    BEGIN {
        ## Split fields with ";".
        FS = OFS = "; "
    }

    {
        $2 = sprintf( "%.2f", $2/5 )
        print $0
    }
' infile

Output:

2012-07-12 15:30:09; 70.64
2012-07-12 15:45:08; 69.48
2012-07-12 16:00:08; 39.52
2012-07-12 16:15:08; 61.64
2012-07-12 16:30:09; 70.52
Persas answered 17/7, 2012 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.