Computing.Net > Forums > Unix > Insert contents of file into variab

Insert contents of file into variab

Reply to Message Icon

Original Message
Name: nmf
Date: January 22, 2007 at 11:44:04 Pacific
Subject: Insert contents of file into variab
OS: mac os x 10.3.9
CPU/Ram: G4 256 mg
Model/Manufacturer: apple
Comment:

How do I put the contents of a file into a variable.
A file called 655.grp contains
"
/Brightwood/ {cat="Brightwood"} ; /East Longmeadow/
{cat="East Longmeadow"} ; /Forest Park/ {cat="Forest
Park"} ;
"
that will be inserted into the middle of an awk statement
the result being

awk '/Brightwood/ {cat="Brightwood"} ; /East
Longmeadow/ {cat="East Longmeadow"} ; /Forest Park/
{cat="Forest Park"} {print $0 ",",cat,",TX," }' data.4 >
data.all

I want to just enter

awk ' $variable {print $0 ",",cat,",TX," }' data.4 > data.all

and have it automatically pull up the contents of the file
as a part of the awk statement.

Anyone have a clue how to do this?

Many thanks


Report Offensive Message For Removal


Response Number 1
Name: nails
Date: January 22, 2007 at 14:04:58 Pacific
Reply: (edit)

The common method for setting the contents of a file to a variable is this way:

var=`cat 655.grp`

I don't know what you are really doing. I think you will have some syntax problems based on the structure of your file 655.grp.

That said, when you have variable data in an awk structure, a method is to use a here document, send the output to a file, and then execute the awk script. Consider this example:

awk '
/Brightword/
{
cat="Brightwood"
print $0","cat",TX"
}
' data.4

Now, I'll show you how to perform the same test awk program by variablizing Brightwood
in a HERE document:

myvar="Brightword"
cat<<HERE >awkfile
/${myvar}/
{
cat="${myvar}"
print \$0","cat",TX"
}
HERE
# end HERE document

The above document creates awkfile. Note the absense of single quotes. Also, note escaping $0 so the shell doesn't expand it.

# create the awk input file
infile="data.4"
# execute the awkfile created above
awk -f awkfile $infile
# end example

The second example should show the same output as the first. Let me know if you have any questions.


Report Offensive Follow Up For Removal

Response Number 2
Name: James Boothe
Date: January 22, 2007 at 15:36:00 Pacific
Reply: (edit)

I tried a hundred things, finally found something that works (on linux). This is as close as I can get.

x=`cat 655.grp`
y='{print $0 ",",cat,",TX,"}'
eval awk \'$x$y\' data.4 > data.all


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Insert contents of file into variab

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 6 Days.
Discuss in The Lounge