3

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

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

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

所以... 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 ......我仍然不在那里。提前致谢

4

3 回答 3

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

甚至更好(感谢 kojiro):

awk '/LUN/ {system("command " $2 $3);}'
于 2013-10-16T22:23:02.910 回答
3

Try using awk followed by xargs

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

Output of awk

64MB /mnt/extent0
64MB /mnt/extent1
10MB /mnt/extent4

Use of xargs with -n 1 (maximum one argument at a time) will execute following set of commands

command -s 64MB /mnt/extent0
command -s 64MB /mnt/extent1
command -s 10MB /mnt/extent4
于 2013-10-16T22:48:43.000 回答
2

一个while循环和一个读取命令:

while IFS= read -r f1 f2 f3; do
    if [[ $f1 == LUN* ]]; do
        some command with $f2 and $f3
    fi
done < input.file
于 2013-10-17T00:38:42.227 回答