Alex Rivera | Logout

How can I assign the match of my regular expression to a variable?

Asked 2009-08-07T21:19:23.433
18

I have a text file with various entries in it. Each entry is ended with line containing all asterisks.

I'd like to use shell commands to parse this file and assign each entry to a variable. How can I do this?

Here's an example input file:

***********
Field1
***********
Lorem ipsum
Data to match
***********
More data
Still more data
***********

Here is what my solution looks like so far:

#!/bin/bash
for error in `python example.py | sed -n '/.*/,/^\**$/p'`
do
    echo -e $error
    echo -e "\n"
done

However, this just assigns each word in the matched text to $error, rather than a whole block.

Edit
Report

1 Answer

0

depending on what you want to do with the variables

awk '
f && /\*/{print "variable:"s;f=0}
/\*/{ f=1 ;s="";next}
f{
   s=s" "$0
}' file

output:

# ./test.sh
variable: Field1
variable: Lorem ipsum Data to match
variable: More data Still more data

the above just prints them out. if you want, store in array for later use...eg array[++d]=s

answered 2009-08-07T23:51:31.940

Your Answer