2017-04-05 57 views
1

我需要在每個逗號之間的每個字符串之後每插入一個小數點。在逗號之間每隔一個數字之後在字符串中插入小數點

some.file:

JAN,334,333,332,331,330,330,329,328,328,327,327,327 

嘗試代碼:

sed -i 's/\B[0-9]\{1\}\>/.&/' some.file 

電流輸出:

JAN,33.4,333,332,331,330,330,329,328,328,327,327,327 

預期輸出:

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7 

我試圖代碼似乎只抓取(看到)該數字串的第二個逗號,在該行不是每個數字串前述不管逗號,。

+0

你只錯過了'g'標誌全部替換,而不只是第一個 – Sundeep

回答

2

用途:

$ echo "JAN,334,333,332,331,330,330,329,328,328,327,327,327" |sed -e "s/\([0-9]\{2\}\)/\1./g" 
JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7 

對於就地更換:

sed -i -e "s/\([0-9]\{2\}\)/\1./g" some.file 

這裏沒有必要的,但一個安全版本可能是:

sed -i -e 's/,\([0-9]\{2\}\)\([0-9]\)/,\1.\2/g' some.file 
+0

這會將'JAN2017'轉換爲'JAN20.17.' – karakfa

2

您可以按以下使用Awk

awk 'BEGIN{FS=OFS=","}{for(i=2;i<=NF;i++) if (length($i) >2) { $i=substr($i,0,2)"."substr($i,3,length($i)); } }1' file 

產生一個輸出作爲

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7 

的想法是通過元件迴路從2nd記錄開始到結束線(高達$NF)並應用邏輯用於具有數字多於2位

substr()是一個POSIX兼容函數,用於從處理的當前記錄中獲取子字符串。

SUBSTR(字符串,開始[,長度])

返回長度個字符數長的子串,起始於字符數目開始。字符串的第一個字符是第一個字符。

2

另一個awk,除以10的所有數字和與一個小數點打印

awk -v RS=, '{if($1==$1+0) printf "%.1f,", $1/10; else printf "%s,",$1}' file | 
sed '$s/,$/\n/' 

JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7 
1

在使用AWK正則表達式替換:

$ awk 'gsub(/[0-9],|[0-9]$/,".&")||1' file 
JAN,33.4,33.3,33.2,33.1,33.0,33.0,32.9,32.8,32.8,32.7,32.7,32.7 

解釋:

  • gsub(/[0-9],|[0-9]$/,".&")全部替換數目+句號+逗號+逗號表示最後一個數字在句尾記錄
  • ||
  • 1只是打印也無妨
1

另一種方法使用sed:

sed -e "s/\b[0-9][0-9]/&./g" 
相關問題