Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using a wrapper and writing a file 1

Status
Not open for further replies.

jasperx

Technical User
Jan 9, 2002
26
US
I have a simple script to format a file which I got to work using the
awk -f scriptname.awk inputFilename > outputfilename

It looks like this:
awk '
BEGIN {FS=","}
{ # loop through fields printing them in 50 char width slots
for (i=1; i<=NF; i++) {
printf(&quot;%-50s\t&quot;, $i)
}
printf(&quot;\n&quot;)
}' $*
Now I am trying the &quot;wrapper&quot; approach and cannot figure out how to output my results to file... Here is what I have:
#! /usr/bin/awk -f
BEGIN {FS=&quot;,&quot;}
{ # loop through fields printing them in 50 char width slots
for (i=1; i<=NF; i++) {
printf(&quot;%-50s\t&quot;, $i) >> OutputFile
}
printf(&quot;\n&quot;) >> OutputFile
}
It gives me this error even when I have created the OutputFile in advance:
awk: null file name in print or getline
 
Omit the redirection within the AWK program itself
Code:
#! /usr/bin/awk -f
BEGIN {FS=&quot;,&quot;}
{ # loop through fields printing them in 50 char width slots
for (i=1; i<=NF; i++) {
    printf(&quot;%-50s\t&quot;, $i)
    }
printf(&quot;\n&quot;)
}

The AWK program itself just writes to the standard output. You change this by using the shell to redirect standard out to wherever you want, like so
Code:
awk -f scriptname.awk inputFilename > outputfilename
 
OK... so that was pretty simple (and helpful)... It would be really nice if I could prompt the user for the input file name and an output file name if they forgot...I have done something like this in a shell script but do not see how to keep awks $1 treatment for fields separate from command line parameters... Here is what I had in mind:
#! /usr/bin/awk -f
#format the cvs file
#
# ************************************************************************
# Variable Declarations
#
noEntryMsgInput=&quot;Please enter the name of the file to format.&quot;
noEntryMsgOutput=&quot;Please enter a name for the ouput file.&quot;
#
# ************************************************************************

if [ -z $1 ] # No inputFile entry- prompt user
then
echo $noEntryMsgInput
read entry
else # Entry- Assign command parameters to inputFile
inputFile=$1
fi

if [ -z $1 ] # No outputFile entry- prompt user
then
echo $noEntryMsgOutput
read entry
else # Entry- Assign command parameters to outputFile
outputFile=$2
fi

BEGIN {
FS=&quot;,&quot;
}
{ # loop through fields printing them in 50 char width slots
for (i=1; i<=NF; i++) {
printf(&quot;%-50s\t&quot;, $i)
}
printf(&quot;\n&quot;)
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top