How to extract two numbers from a word and store then in two separate variables in bash?

StackOverflow https://stackoverflow.com/questions/12744706

  •  05-07-2021
  •  | 
  •  

質問

I believe my question is very simple for someone who knows how to use regular expressions, but I am very new at it and I can't figure out a way to do it. I found many questions similar to this, but none could solve my problem.

In bash, i have a few variables that are of the form nw=[:digit:]+.a=[:digit:]+ for example, some of these are nw=323.a=42 and nw=90.a=5 I want to retrieve these two numbers and put them in the variables $n and $a. I tried several tools, including perl, sed, tr and awk, but couldn't get any of these to work, despite I've been googling and trying to fix it for an hour now. tr seems to be the fittest though.

I'd like a piece of code which would achieve the following:

#!/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...
役に立ちましたか?

解決

If you trust your input, you can use 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

他のヒント

if you do not trust your input :) use this:

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

result in:

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

for sure there are more elegant ways, this is just a quick working hack

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top