Reputation: 1467
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.
Upvotes: 2
Views: 28361
Reputation: 58500
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
Upvotes: 2
Reputation: 15986
If you want to continue down the bash 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
Upvotes: 7
Reputation: 10304
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.
Upvotes: 3
Reputation: 77065
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
Upvotes: 4