【问题标题】:Read line containing specific text in a shell script variable读取 shell 脚本变量中包含特定文本的行
【发布时间】:2018-04-12 11:30:31
【问题描述】:

我在 shell 脚本中有一个变量,如下所示。每行由换行符分隔。

var="This is the first line
This is the second line
This is the third line
/home/usr/new/foo.txt
This is the forth line
This is the fifth line"

现在我需要读取其中包含.txt 的行并将其存储在另一个变量中。

another_var=/home/usr/new/foo.txt

【问题讨论】:

  • 像魅力一样工作,谢谢:)
  • 感谢您发现它很有用。您还可以通过您尝试过的相关努力来更新问题,以便将来有所帮助吗?
  • 我认为grep 可以选择行...如var2="$(echo "$var" | grep '.txt$')"

标签: bash shell aix


【解决方案1】:

在最新版本的bash 中,您应该可以使用mapfile 命令来解析多行字符串。我们将字符串解析为一个数组并匹配包含 glob 字符串.txt 的行并将其打印为

mapfile -t new_array <<< "$var"

for element in "${new_array[@]}"; do 
    if [[ $element == *".txt"* ]]; then
        new_var="$element"
        break
    fi
done

【讨论】:

    【解决方案2】:

    这是更通用的。

    #!/bin/bash
    
    var="This is the first line
    This is the second line
    This is the third line
    /home/usr/new/foo.txt
    This is the forth line
    This is the fifth line"
    
    dog="$( echo "$var" | grep txt )"
    echo $dog
    

    我使用过 bash,但我相信这也适用于 ksh。

    我没有注意到 Zsigmond 已经提出了这个建议。

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多