I have an output in one format that I need to basically read line by line and reformat into another file. I was originally going to try do this in Java, but Java does not have a lot of good classes for text processing.

Here is an example of my input file: (store-orders.txt)

Items purchased by TexasStore:
Orders: 7 Unique: 4 OutofStock: 0
StockID DepartmentID Instances
34.34 12 10
34.3 12 6
2.75 6 55

Items purchased by FloridaStore:
Orders: 6 Unique: 6 OutofStock: 1
StockID DepartmentID Instances
34.27 12 78
33.3 6 27
5.75 7 33

The file contains items ordered, the department that ordered it, and the quantity.
All I really need to do is extract the store name for each group and insert it inline before the "34.34 12 10" so that I can import it into a spreadsheet.

My finished file would look something like this:

TexasStore 34.34 12
TexasStore 34.3 12
TexasStore 2.75 6
FloridaStore 34.27 12
FloridaStore 33.3 6
FloridaStore 5.75 7

This seemed like it would be an easy problem to solve, but it seems more difficult now than I anticipated.

There are a couple lines of information I don't need, but I could quickly make them go away with something like 'cat store-orders.txt | grep -v Orders | grep -v StockID'

For he next part, I am not really sure how best to go about it.

What I need to do is read a line, and if the line contains the store name, awk '{print $4}' and assign that value to a variable.

Here is a pseudo example.

while (next.line() != null) {

if ((grep Store $line) == true)
$store = (awk '{print $4}');

if ($line == ^number)
print.line ($store $1 $2);


A shell script seems like the least complex way to solve this, so I though I would ask for a hand here.

Hey There

Maybe this would help - not in front of a terminal right now, but this should be close if it's not right, I hope :)

This assumes that you're only reading in one file with one store.. extrapolate as necessary

while read line
   if [ $store -eq 0 ]
       store=`echo $line|awk '{ if ( $0 ~ /^Items / ) print $4}'
       echo $line|awk '{print " $store " $1 " " $2}' >>$store.txt
done <store-orders.txt

Best wishes,


With Awk:

awk '/^Items/{sub(/Items purchased by /,"");store=$1}
/^[0-9]/{printf "%s %s\n",store,$0}' FS=":" store-orders.txt>your_new_file.txt

Use nawk or /usr/xpg4/bin/awk on Solaris.