【问题标题】:Bash script to read a text file and then output each line into variables用于读取文本文件然后将每一行输出到变量中的 Bash 脚本
【发布时间】:2012-02-13 18:06:14
【问题描述】:

我有一个名为 test 的文件,其中包含未知的行数:

<label>blogname</label><type>string</type>
<label>blog description</label><type>text</type>

我想使用 SED 或 AWK 来读取该文件并将每个标签和每种类型存储到一个单独的变量中,甚至更好地存储到一个数组中。

此示例将在文件中输出标签的内容:

awk -vRS="</variable>" '/<variable>/{gsub(/.*<variable>/,"");print}' test >result

但我需要每一行的内容,并通过每个标签的内容将它们分开,给我这样的东西:

label="blogname"
type="string"

然后我需要使用 do while 脚本处理数组。

我已经为这个问题寻找了几个小时的解决方案,但没有运气。

【问题讨论】:

  • 您可能会编写一个awk 脚本来输出一行带有标签的行,然后是一行带有类型的行,并在bash 的while 循环中使用read 将值放入大批。查找 read 和 bash 数组。

标签: arrays bash multidimensional-array sed


【解决方案1】:

永远不应该真正使用以下代码。它解决了问题,但 bash 脚本并不是您真正想要用于此类任务的。

#!/bin/sh
while read line; do
    label=`echo $line | sed -n 's|^.*<label>\(.*\)</label>.*$|\1|p'`
    type=`echo $line | sed -n 's|^.*<type>\(.*\)</type>.*$|\1|p'`
    echo "label:" $label
    echo "type:" $type
    echo
done

编辑:受 perelman 评论启发的另一个版本

#!/bin/sh
sed -n 's|^<label>\(.*\)</label><type>\(.*\)</type>.*$|\1\n\2|p' | while read label; do
    read type
    echo "label:" $label
    echo "type:" $type
    echo
done

【讨论】:

  • 提供的解决方案很棒,但我尝试添加第三个变量,但它似乎不起作用
【解决方案2】:

这可能对你有用:

sed 's/<\([^>]*\)>\([^<]*\)<\/\1>/&\n/g' file |
sed '/^\s*$/d;s/<\([^>]*\)>\([^<]*\)<\/\1>/\1="\2"/'
label="blogname"
type="string"
label="blog description"
type="text"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 2022-01-11
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2020-08-15
    相关资源
    最近更新 更多