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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write to multiple files in awk via another file...

Status
Not open for further replies.

bondtrails

Technical User
Nov 19, 2002
31
US
Hey everyone,
newbie #1 still learning awk. I need some help: I have a file, each record contains data and a filename. I want my awk program to append each record to a file whose file name is on that records. For example, if file FILE_A.txt contains:
filename_1.txt data data data
filename_1.txt more data more data
filename_2.txt new data new data
filename_9.txt some other new data

then I want my awk program to write the data to the appropriate file.

Can some good soul help out a newbie??

thanks!!

--Bondster!
 
This will print everything including the filename to the file

{print >> $1}

This will print just the data following the filename to the file, but will compress multiple consecutive spaces into 1 space

{fn = $1;$1="";print >> fn}

This will print just the data following the filename with spacing preserved.

{fn=$1;sub(/^ *[^ ]* */,"");print >> fn}

If you are creating a lot of files, you may need to put a

;close(fn)

after the print


CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
CaKiwi,
{print >>$1) works fine, it writes to the appropriate file, but it also prints to STDOUT (screen). How can I suppress screen printout?

Thanks!

--Bondster!!
 
It shouldn't write to stdout. What else do you have in your script?

CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
Hi CaKiwi,
here's my program. Don't know why it prints to STDOUT

awk -f Program.awk dataFile.txt

# ========= program1.awk ==========
outfile = substr($0,9,18)
gsub(/ /,"",outfile)
{print >>outfile ; close(outfile)}

The only way to not get printout on my screen is to redirect STNDOUT to > /dev/null

--Bondster!
 
You need braces around the whole program

# ========= program1.awk ==========
{
outfile = substr($0,9,18)
gsub(/ /,"",outfile)
print >>outfile
close(outfile)
}

It is printing to stdout because substr or gsub is returning true which triggers the default action to print to stdout.


CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
ahh!! CaKiwi, you are a ray of light!!

--Bondster!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top