I have this text file, which looks like this

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

And I need is to get it to look like this:

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

I am aware of the fact, that I need two for loops to get this. I did some tests, but... well, it didn't end up well.

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

Could anyone please kick me back on the road? I tried bunch of variete ways, but I am not getting anywhere. Thanks.

有帮助吗?

解决方案

If you want to continue down the shell road, you can do something like this:

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

其他提示

Text parsing is best done with awk:

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

Using awk

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

Here's another awk alternative:

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

If a line begins with 'Item', save the item name in ITM. If the line does not begin with 'Item', print the previously saved item name (ITM), '=>', and the sub item. Splitting on : makes it easier to get the item name.

The assumption is that groups of subitems will always be preceded by an Item: entry, so the variable ITM should always have the name of the current group.

TXR Solution:

@(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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top