Shell/Bash解析文本文件

Fan*_*icD 2 bash shell awk parsing text-processing

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

Item:
SubItem01
SubItem02
SubItem03
Item2:
SubItem0201
SubItem0202
Item3:
SubItem0301
...etc...
Run Code Online (Sandbox Code Playgroud)

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

Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301
Run Code Online (Sandbox Code Playgroud)

我知道这个事实,我需要两个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
Run Code Online (Sandbox Code Playgroud)

谁能请我回到路上?我尝试了各种各样的方式,但我没有得到任何地方.谢谢.

Dig*_*uma 6

如果你想继续沿着 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
Run Code Online (Sandbox Code Playgroud)