【问题标题】:find a option in string split by space in bash在bash中按空格分割的字符串中找到一个选项
【发布时间】:2014-03-31 22:05:08
【问题描述】:

我有一个这样的字符串,将其命名为 Options:

"printer-is-accepting-jobs=true printer-is-shared=false printer-location=Library printer-make-and-model='HP LaserJet 600 M601 M602 M603' printer-state=3"

它们是“options=values”格式,以空格分隔。但“打印机制造和型号”对空格有价值。

尝试过的命令:

for word in $Options; do echo $word; done

所有 HP LaserJet 600 M601 M602 M603 都是拆分的。

在 bash 命令中如何处理?

【问题讨论】:

标签: bash split substring


【解决方案1】:

使用grep -oP

grep -oP "printer-make-and-model='\K[^']*" <<< "$s"
HP LaserJet 600 M601 M602 M603

或者使用 sed:

sed "s/^.*printer-make-and-model='\([^']*\).*/\1/" <<< "$s"
HP LaserJet 600 M601 M602 M603

【讨论】:

  • 谢谢!对不起,忘了提,我在 Mac 上。它没有 -P 选项,-P 是干什么用的?
  • 我也在 OSX 上,grep -P 可用(-P 表示 PCRE)
  • :) @jaypal 您可以从我的回答中获取任何正则表达式/代码。没有版权,因为我从 SO 和其他论坛了解到大部分内容。
【解决方案2】:

Anubhava's 正则表达式很好,所以如果你没有grep -P 选项,那么你可以试试:

ack 命令:

$ ack -ho "printer-make-and-model='\K[^']*" <<< "$options"
HP LaserJet 600 M601 M602 M603

Perl:

$ perl -nle "print $+{f} if /printer-make-and-model='(?'f'\K[^']*)/" <<< "$options"
HP LaserJet 600 M601 M602 M603

【讨论】:

    【解决方案3】:

    由于需要解析选项,可以使用getopt。但是,这需要使用邪恶的eval 命令。所以要小心你的输入。

    $ string="printer-is-accepting-jobs=true printer-is-shared=false printer-location=Library printer-make-and-model='HP LaserJet 600 M601 M602 M603' printer-state=3"
    $ eval a=("$string")
    $ eval b=($(getopt --long printer-make-and-model: -- ${a[@]/#/--} 2>/dev/null))
    $ echo "${b[1]}"
    HP LaserJet 600 M601 M602 M603
    

    【讨论】:

    • 在我的 Mac 上,echo "${b[1]}" 得到 "printer-make-and-model:"
    • 坦率地说,我没有在 mac 上尝试过,但我认为,mac 上的 getopt 提供的输出与我的系统上不同。试试for x in "${b[@]}; do echo $x; done看看getopt输出中的参数顺序是否发生了变化...
    【解决方案4】:

    您可以使用多个 awk 语句来做到这一点:

    while read record; do
        while read key value; do
            echo "K=($key) V=($value)"
        done< <(awk -F"=" '{printf("%s %s\n", $1, $2)}' <<< $record)
    done< <(awk -F"printer-" '{for(i=2;i<NF;i++){printf("printer-%s\n", $i)}}' <<< $string)
    

    这将拆分为输出成键值对。

    【讨论】:

    • @"Tim Verhoeven",太棒了!你的给我整个清单!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多