【问题标题】:bash + awk + grep.... parse and save variablebash + awk + ​​grep .... 解析并保存变量
【发布时间】:2013-10-17 08:38:42
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这个问题似乎跑题了,因为它是关于 bash 的,更适合 Unix & LinuxSuper User
  • @ColeJohnson 解析和执行一个文件,非常适合Stack Overflow
  • @fedorqui 关键字更适合
  • eval `sed -n -e"s/^ *LUN[0-9] \([^ ]*\) \([^ ]*\).*$/exec command -s \1 \2/p" test.txt`eval `grep "^ *LUN" test.txt | awk '{print "exec command -s "$2" "$3}'` 怎么样
  • 每次我在谷歌上搜索有关 bash、awk、sed 和 grep 的示例信息时,99% 的命中都是堆栈溢出 url....所以我认为这是合适的。我很好奇什么是合适的。

标签: bash awk grep


【解决方案1】:

使用 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);}'

【讨论】:

  • 哦,我不知道system()awk中的存在。更新以反映,谢谢!
  • 我可以堆叠一个系统吗("command" $2 $3);系统(“命令” $3);每个??我喜欢一个班轮,它干净又短。
  • 更大的问题似乎不是初始化,而是重新初始化已经存在的 lun 并创建第二个实例
  • 我可以双栈读取变量为 $c 的前一行吗?awk '/UnitInquiry/ {print $2, $3}' $ctld_config |而读 c ;执行 awk '/LUN/ {print $2, $3}' $ctld_config |同时阅读 a b ;做
  • 或者是 awk '/LUN/ {print $2, $3}' '/UnitInquiry/ {print $2}' /etc/ctld.conf |在阅读 a b c 时;做??
【解决方案2】:

尝试使用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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2018-04-25
      • 2022-11-24
      相关资源
      最近更新 更多