在 shell 脚本变量中读取包含特定文本的行

Read line containing specific text in a shell script variable

我在 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

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

这更通用。

#!/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 已经提出了这个建议。