Daniel
Daniel

Reputation: 2726

How to replace a word in a line that has a character using shell scripts

I have a file, its content is something like this

#Time value
2.5e-5 1.3
5e-5 2.7
7.5e-5 1.1
0.0001 5.9
0.000125 5.8
0.00015 3
......

How can I replace the line that is with letter e in it (the scientific notation), so that the final file would be

#Time value
0.000025 1.3
0.00005 2.7
0.000075 1.1
0.0001 5.9
0.000125 5.8
0.00015 3
...... 

Is shell script able to do this?

for (any word that is using scientific notation)
{
    replace this word with decimal notation
}

Upvotes: 1

Views: 115

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85775

With awk:

$ awk '$1~/e/{printf "%f %s\n", $1,$2}$1~!/e/{print}' file
0.000025 1.3
0.000050 2.7
0.000075 1.1
0.0001 5.9
0.000125 5.8
0.00015 3

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

If you're familiar with the printf() function in C, there's a similar built-in shell command:

$ printf '%f' 2.5e-5
0.000025
$ printf '%f' 5e-5
0.000050

To use this in a script, you could do something like:

while read line; do
    if [[ $line = \#* ]]; then
        echo "$line"
    else
        printf '%f ' $line
        echo
    fi
done < times.txt

This goes through some trouble to skip the #Time value comment. If you could get rid of that line, then it'd be even simpler:

while read a b; do printf '%f %f\n' $a $b; done < times.txt

Upvotes: 4

Related Questions