Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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 beingawk '/Brightwood/ {cat="Brightwood"} ; /East
Longmeadow/ {cat="East Longmeadow"} ; /Forest Park/
{cat="Forest Park"} {print $0 ",",cat,",TX," }' data.4 >
data.allI 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

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.4Now, 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 documentThe 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 exampleThe second example should show the same output as the first. Let me know if you have any questions.

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

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |