【问题标题】:getting a column of a specific line in bash在bash中获取特定行的列
【发布时间】:2014-08-09 17:37:48
【问题描述】:

我有这个命令:

id=$(xl list|egrep $Name| tr -s ' ' | cut -d ' ' -f 2)

其中xl list 输出如下内容:

Name                                        ID   Mem VCPUs  State   Time(s)
Domain-0                                     0  5923     8     r-----    4266.0
new_redhat9-clone                            3  1027     1     r-----    1019.6
new_redhat9                                  4  1027     1     -b----      40.1

实际上我想获得给定NameID。这在Name=new_redhat9-clone 时有效(它返回3)但在Name=new_redhat9 时不起作用(它返回:3 4!!!!)。 怎么了?!!!

【问题讨论】:

    标签: bash scripting command


    【解决方案1】:

    grep 搜索字符串模式匹配。 egrep new_redhat9 匹配“new_redhat9”和“new_redhat9-clone”。尝试在模式后添加空格(或 \t),像这样重写

    id=$(xl list|egrep 'new_redhat9 '| tr -s ' ' | cut -d ' ' -f 2)
    

    【讨论】:

    • 但是我通过变量来命名! id=$(xl list|egrep $dom_name| tr -s ' ' | cut -d ' ' -f 2)如何为变量做到这一点?
    • 尝试 id=$(xl list|egrep "$dom_name "| tr -s ' ' | cut -d ' ' -f 2)
    • Advanced Bash-Scripting Guide 添加到书签。学习 bash 脚本的最佳书籍 :)
    • 备注:在'new_redhat9 ' 中你也可以使用\s 代替空格来匹配空格和制表符;或\b 匹配单词边界。更重要的是,您可能会考虑将您的模式锚定在行首(或者如果有像 'redhat9-clone' 这样的名称到 grep,也会出现同样的问题)。那将使:egrep "^$dom_name\b".
    【解决方案2】:

    您可以使用awk 代替egrep,tr and cut 命令,

    id=$(xl list | awk '$1=="new_redhat9" {print $2}')
    

    Awk 命令在xl list 输出的第一列中搜索确切的字符串new_redhat9。如果找到,则将相应记录上的 column2 的值存储到变量id

    您可以通过echo $id 命令查看输出。

    如果名称存储在变量中,请尝试以下命令

    id=$(xl list | awk -v var=$Name '$1==var {print $2}')
    

    【讨论】:

    • 我知道这个,但实际上这个命令是这样的: id=$(xl list|egrep $dom_name| tr -s ' ' | cut -d ' ' -f 2) and awk doen不像你说的那样工作。
    • 为什么有效?试试awk -v var=$(dom_name) '$1=="var" {print $2}'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-04-14
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多