Alan C
Alan C

Reputation: 181

How can I do a for loop in shell

I have the following in a file:

[Class:ABCD_EFGH_IJK]
list.0=VALUE001*
list.1=VALUE002*
list.2=VALUE003*
list.3=VALUE004*
[Class:ABCD_EFGH_IJK:app:ABCD_EFGH_IJK]
condition=true

[Class:LMNO_PQRS_TUV]
list.0=VALUE004*
list.1=VALUE005*
list.2=VALUE006*
list.3=VALUE007*
[Class:LMNO_PQRS_TUV:app:LMNO_PQRS_TUV]
condition=true

I have another script that runs using the class name and list value as its arguments. For example:

./myscript VALUE001* ABCD_EFGH_IJK

I need use a for loop to iterate over each class and grab each value to run my script. How can I achieve this?

Upvotes: 0

Views: 60

Answers (2)

Walter A
Walter A

Reputation: 19982

A terrible example (too complex) using the Hold space in sed is

sed -nr '/\[Class:/ {s/\[Class:(.*)\]/\1/;h};/list/{G;s#.*=(.*)\n#./myscript \1 #p}' file

In words:
When you see a line with Class:, copy the classname into the Hold space. When you see a line with list, append the Hold space (the classname) to the current line,
and use the inserted newline character for modifying the first part.
Print the line.

The # is used when the replacement string has a \.
Remembered matched strings in () are recalled with \1.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203189

This is what you asked for:

$ awk -F'[]:=[]' '/Class:/{class=$3} /^list/{print $2, class}' file |
    xargs -n2 echo ./myscript
./myscript VALUE001* ABCD_EFGH_IJK
./myscript VALUE002* ABCD_EFGH_IJK
./myscript VALUE003* ABCD_EFGH_IJK
./myscript VALUE004* ABCD_EFGH_IJK
./myscript VALUE004* LMNO_PQRS_TUV
./myscript VALUE005* LMNO_PQRS_TUV
./myscript VALUE006* LMNO_PQRS_TUV
./myscript VALUE007* LMNO_PQRS_TUV

Remove the echo when you're ready to actually have ./myscript called.

Upvotes: 2

Related Questions