2015-10-19 20 views
1

我想將每個數字行與數值(例如2)相乘,除了行有標題(帶空格的字符行)。在linux/awk/bash中僅將行與數值相乘

Input.file

fixedStep chrom=chr1 start=9992 step=1 
3 
6 
10 
23 
... 
fixedStep chrom=chr1 start=11166 step=1 
2 
4 
6 
... 

期望輸出

fixedStep chrom=chr1 start=9992 step=1 
6 
12 
20 
46 
... 
fixedStep chrom=chr1 start=11166 step=1 
4 
8 
12 
... 

我的代碼:

while read line; do echo 2*$line; done <Input.file | bc 

此代碼乘法完美,但不留頭,因爲它是。誰能幫忙?我的代碼

輸出示例:

(standard_in) 1: illegal character: S 
(standard_in) 1: parse error 
(standard_in) 1: parse error 
(standard_in) 1: parse error 
6 
12 
20 
46 
... 

回答

1

您可以使用AWK:

awk 'NF==1{$1 *= 2} 1' file 
fixedStep chrom=chr1 start=9992 step=1 
6 
12 
20 
46 
0 
fixedStep chrom=chr1 start=11166 step=1 
4 
8 
12 

,或者檢查是否第一個字段是數字:

awk '$1*1{$1 *= 2} 1' file 
1

Perl的解決方案:

perl -lpe '$_ *= 2 if /^[0-9]+$/' Input.file 
  • -l處理換行符。
  • -p逐行讀取輸入並打印。
  • $_是主題變量。如果它僅包含數字,則將其乘以2.
1

當我試圖保持接近OP的解決方案時,請僅對具有空格的字段使用bc。

while read line; do 
     if [[ "${line}" = *\ * ]]; then 
      echo $line 
     else 
      echo 2*$line | bc 
     fi 
done <Input.file 

您可以通過((line *= 2))更換bc和顯示結果改善這一點。當您使用此方法時,您可以跳過if語句:

while read line; do 
    ((line *= 2)) 2>/dev/null 
    echo $line 
done <Input.file