bash + awk + ​​grep ....解析并保存变量

时间:2013-10-16 22:20:55

标签: bash awk grep

我有一个配置文件......

# LogicalUnit section
[LogicalUnit1]
  LUN0 /mnt/extent0 64MB
[LogicalUnit2]
  LUN0 /mnt/extent1 64MB
[LogicalUnit3]
  LUN0 /mnt/extent4 10MB

我需要从以LUN开头的所有行读取字段2和3到变量中,并使用这些变量执行shell命令

so ... LUN0,我将字段2和字段3读入变量

/mnt/extent4 10MB

所以说

A=/mnt/extent4
B=10MB
var1=A
var2=B

exec command -s $B $A 

我得到逻辑,但无法弄清楚如何循环文件,读取2个字段并将它们传递回bash。很多帮助升值,我花了两天时间用bash grep和awk ......我还没有。提前谢谢

3 个答案:

答案 0 :(得分:4)

使用awk,您可以获得值:

$ awk '/LUN/ {print $2, $3}' a
/mnt/extent0 64MB
/mnt/extent1 64MB
/mnt/extent4 10MB

然后管道处理:

$ awk '/LUN/ {print $2, $3}' a | while read a b
> do
> echo "this is $a and this is $b"
> echo "exec $a $b"
> done
this is /mnt/extent0 and this is 64MB
this is /mnt/extent1 and this is 64MB
this is /mnt/extent4 and this is 10MB

或者

$ awk '/LUN/ {print $2, $3}' a | while read a b; do echo "this is $a and this is $b"; echo "exec $a $b"; done
this is /mnt/extent0 and this is 64MB
exec /mnt/extent0 64MB
this is /mnt/extent1 and this is 64MB
exec /mnt/extent1 64MB
this is /mnt/extent4 and this is 10MB
exec /mnt/extent4 10MB

甚至更好(thanks kojiro):

awk '/LUN/ {system("command " $2 $3);}'

答案 1 :(得分:3)

尝试使用awk后跟xargs

awk '$1~/LUN/ {print $3, $2}' file | xargs -n 1 command -s

awk

的输出
64MB /mnt/extent0
64MB /mnt/extent1
10MB /mnt/extent4

使用xargs-n 1(一次最多一个参数)将执行以下命令集

command -s 64MB /mnt/extent0
command -s 64MB /mnt/extent1
command -s 10MB /mnt/extent4

答案 2 :(得分:2)

while循环和读取命令:

while IFS= read -r f1 f2 f3; do
    if [[ $f1 == LUN* ]]; do
        some command with $f2 and $f3
    fi
done < input.file