【问题标题】:Shell/Bash parsing text fileShell/Bash 解析文本文件
【发布时间】:2014-04-28 02:10:22
【问题描述】:

我有这个文本文件,看起来像这样

Item:
SubItem01
SubItem02
SubItem03
Item2:
SubItem0201
SubItem0202
Item3:
SubItem0301
...etc...

我需要让它看起来像这样:

Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301

我知道我需要两个 for 循环来获得这个事实。我做了一些测试,但是……嗯,结果并不好。

for(( c=1; c<=lineCount; c++ ))
do

   var=`sed -n "${c}p" TMPFILE`
   echo "$var"

   if [[ "$var" == *:* ]];
   then
   printf "%s->" $var
   else
   printf "%s\n"
   fi
done

有人能把我踢回路上吗?我尝试了很多不同的方法,但我无处可去。谢谢。

【问题讨论】:

  • 不,你不需要两个循环。这是作业吗?我们遇到过同样问题的其他人,也误以为嵌套循环是不久前的正确解决方案。

标签: bash shell parsing awk text-processing


【解决方案1】:

文本解析最好使用awk

$ awk '/:$/{sub(/:$/,"");h=$0;next}{print h"=>"$0}' file
Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301

【讨论】:

    【解决方案2】:

    如果你想继续 shell 之路,你可以这样做:

    item_re="^(Item.*):$"
    while read -r; do
        if [[ $REPLY =~ $item_re ]]; then
            item=${BASH_REMATCH[1]}
        else
            printf "%s=>%s\n" "$item" "$REPLY"
        fi
    done < file.txt
    

    【讨论】:

    • 谢谢,这可能正是我想要的!
    【解决方案3】:

    使用 awk

    awk '/:/{s=$1;next}{print s OFS $0}' FS=: OFS="=>" file
    

    【讨论】:

    • 谢谢,感谢您的帮助!
    • 如果我的声誉足够高,请确保我会这样做。
    【解决方案4】:

    这是另一个awk 替代方案:

    awk -F: '/^Item/{ITM=$1} !/^Item/{print ITM"=>"$0}'
    

    如果一行以“项目”开头,则将项目名称保存在 ITM 中。如果行以“Item”开头,则打印之前保存的项目名称 (ITM)、“=>”和子项目。拆分 : 更容易获取项目名称。

    假设子项组之前总是有一个 Item: 条目,因此变量 ITM 应该始终具有当前组的名称。

    【讨论】:

    • 您能解释一下吗?目前您的答案不完整。
    • @bjb568 我已经添加了解释。这有帮助吗?
    【解决方案5】:

    TXR解决办法:

    @(collect)
    @left:
    @  (collect)
    @right
    @  (until)
    @(skip):
    @  (end)
    @(end)
    @(output)
    @  (repeat)
    @    (repeat)
    @left=>@right
    @    (end)
    @  (end)
    @(end)
    
    $ txr regroup.txr data.txt
    Item=>SubItem01
    Item=>SubItem02
    Item=>SubItem03
    Item2=>SubItem0201
    Item2=>SubItem0202
    Item3=>SubItem0301
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2020-02-09
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多