2013-01-18 28 views
1

我有一個文件有一個字符線替換詞,它的內容是這樣的如何在使用shell腳本

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

我如何可以替換與字母e在它的行(科學記數法),以便最終文件將是

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

shell腳本能夠做到這一點嗎?

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

回答

1

隨着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 
4

如果你熟悉C的printf()功能,還有一個類似的內置shell命令:

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

要在腳本中使用這個,你可以這樣做:

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

這經歷了一些麻煩,跳過#Time value評論。如果你能擺脫這條線的,那麼它會是更簡單:

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

好吧,但如何找到這些線,並將字包含'e'做這個'printf()'? – Daniel

+1

@丹尼爾,你可以用'awk'輕鬆做到這一點。 –