1

I have a file called test that contains an unkown number of lines:

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

I would like to use SED or AWK to read that file and store each label and each type into a separate variable or even better into an array.

this example would output the content of label in a file:

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

But I need to the contents of each line and separate them by the content of each tag to give me something like this:

label="blogname"
type="string"

I would then need to process the array with a do while script.

I have been searching for a solution to this for hours but had no luck.

1
  • You could probably write an awk script to output a line with the label followed by a line with the type and use read in a while loop in bash to put the values into an array. Look up read and bash arrays.
    – perelman
    Feb 12, 2012 at 21:22

2 Answers 2

0

The following code should never really be used. It solves the problem, but a bash script is not really what you want to use for such a task.

#!/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

Edit: Another version inspired by the comment by 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
1
  • The solution provided was great but I tried to add a third variable but it does not seem to work Feb 12, 2012 at 23:26
0

This might work for you:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.