2016-01-20 38 views
0

我想在第二列的txt文件做一些數學運算,但有些行不是數字,我只想在有數字的行上操作,並保持其他行不變運行數學,忽略非數字值

txt文件,像下面

aaaaa 
1 2 
3 4 

我怎樣才能做到這一點?

+1

請確認您想_pure Bash_解決方案 - 而不是調用標準的Unix工具,如'從猛砸awk'。 – mklement0

+2

可以說,給出一個答案http://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash/806923#806923這變得微不足道。 –

回答

1

加倍任何行第二列不包含任何字母的內容可能看起來有點像在本地的bash以下幾點:

#!/bin/bash 

# iterate over lines in input file 
while IFS= read -r line; do 
    if [[ $line = *[[:alpha:]]* ]]; then 
    # line contains letters; emit unmodified 
    printf '%s\n' "$line" 
    else 
    # break into a variable for the first word, one for the second, one for the rest 
    read -r first second rest <<<"$line" 

    if [[ $second ]]; then 
     # we extracted a second word: emit it, doubled, between the first word and the rest 
     printf '%s\n' "$first $((second * 2)) $rest" 
    else 
     # no second word: just emit the whole line unmodified 
     printf '%s\n' "$line" 
    fi 
    fi 
done 

這從標準輸入讀取和寫入到stdout,所以使用的東西像:

./yourscript <infile >outfile 
0

感謝所有,這是我使用本網站第二次,我發現這是非常實用,它可以得到答案很快

我人所以在下面找到

#!/bin/bash 
FILE=$1 

while read f1 f2 ;do 

if[[$f1 != *[!0-9]*]];then 
    f2=`echo "$f2 -1"|bc` ; 
    echo "$f1 $f2" 
else 
    echo "$f1 $f2" 
fi 

做<%FILE一個答案

+0

正如在這裏給出的,這個答案不起作用 - 也許你在輸入表單時忽略了一些空格? –

+1

還有其他的錯誤,比如在輸出中輸出'$ 2'而不是'$ f2',並且如果你想要的值都是整數,那麼在shell中使用內置數學,而不是' bc':'f2 = $((f2-1))' –