2012-10-05 21 views
0

我相信我的問題對於那些知道如何使用正則表達式的人來說非常簡單,但我對它很新穎,而且我無法想出辦法。我發現了很多與此類似的問題,但沒有人能解決我的問題。例如,其中一些是nw = 323。a = 42和nw = 90.a = 5 我想檢索這兩個數字,並把它們放在變量$ n和$ a中。 我嘗試了幾種工具,包括perl,sed,tr和awk,但無法獲得任何這些工作,儘管我一直在使用Google搜索並試圖修復它一個小時。 tr似乎是最適合的。如何從一個單詞中提取兩個數字,然後存儲在bash中的兩個單獨變量中?

我想一段代碼,這將實現以下目標:如果你相信你的輸入

#!/bin/bash 
ldir="nw=64.a=2 nw=132.a=3 nw=4949.a=30" 
for dir in $ldir; do 
    retrieve the number following nw and place it in $n 
    retrieve the number following a and place it in $a 
done 
... more things... 

回答

1

,您可以使用eval

for dir in $ldir ; do 
    dir=${dir/w=/=}  # remove 'w' before '=' 
    eval ${dir/./ }  # replace '.' by ' ', evaluate the result 
    echo $n, $a   # show the result so we can check the correctness 
done 
+0

這工作!非常感謝! 我會使用這一個,因爲我的輸出已經過濾了 'ldir ='ls | grep -E'nw = [[:digit:]] + \。a = [[:digit:]] +''' 你能否解釋一下這是如何實現的?它有什麼作用? –

+0

@FerdinandoRandisi:查看評論。 – choroba

1

,如果你不信任你的輸入:)使用:

ldir="nw=64.a=2 nw=132.a=3 nw=4949.a=30" 

for v in $ldir; do 
    [[ "$v" =~ ([^\.]*)\.(.*) ]] 
    declare "n=$(echo ${BASH_REMATCH[1]}|cut -d'=' -f2)" 
    declare "a=$(echo ${BASH_REMATCH[2]}|cut -d'=' -f2)" 
    echo "n=$n; a=$a" 
done 

結果:

n=64; a=2 
n=132; a=3 
n=4949; a=30 

肯定有更優雅的方式,這僅僅是一個快速的工作黑客

+0

這很有趣,但它是如何工作的? –

+0

更簡單:'IFS =。閱讀nwStr aStr <<<「$ v」;聲明「$ {nwStr/nw/n}」「$ aStr」;'。 – chepner

+0

Ferdinando,'[[「$ v」=〜([* \。] *)\。(。*)]] regex正在用匹配的字符串填充$ BASH_REMATCH var。在nw = 64.a = 2的情況下,匹配將如下所示:「0:nw = 64.a = 2」,「1:nw = 64」和「2:a = 2」。然後簡單地使用'cut'來「分割」它通過'=' – 2012-10-05 16:10:02

0
ldir="nw=64.a=2 nw=132.a=3 nw=4949.a=30" 
for dir in $ldir; do 
    #echo --- line: $dir 
    for item in $(echo $dir | sed 's/\./ /'); do 
     val=${item#*=} 
     name=${item%=*} 
     #echo ff: $name $val 
     let "$name=$val" 
    done 
    echo retrieve the number following nw and place it in $nw 
    echo retrieve the number following a and place it in $a 
done 
相關問題