2015-10-19 83 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