create a file with filename=$5
Page 1 of 1

Author:  porchrat [ Mon Sep 29, 2008 8:38 am ]
Post subject:  create a file with filename=$5

Hi all. New to this forum so forgive me if I have posted this in the wrong place...if so please feel free to move it or ask for it to be moved.

How would one use awk (or something similar...I just thought awk would be perfect) to create a file with a filename taken from field 5 in the first line?

currently I run this script to extract smaller files from one large text file based on the occurrence of '3' at the end of the line:

cat $1 |while read line; do
   echo $line |grep $stopword && filecounter=$(( filecounter +1 ))
   echo $line >> table.$filecounter

However as you can see this merely creates files named table.1, table.2....table.n.

I would like to get this script to take field 5 from the first line of each new file and use that as the filename. I tried this:

cat $1 | while read line; do
   echo $line | grep $stopword && filesuffix=$( awk '{print $5}' )
   echo $line >> table$filesuffix

However it keeps telling me there is an ambiguous redirect. I would've thought that the "awk" would only come into effect when "grep $stopword" evaluates true and so would therefore only print field 5 from that one line being echoed at that point?

Any suggestions would be most appreciated.

Author:  Daenyth [ Wed Oct 01, 2008 8:06 pm ]
Post subject: 

I would do it more like...
< $1 while read line; do
    tablesuffix="$(awk "/$stopword/ { print \\\$5 }")"
    [ -n "$tablesuffix" ] && echo $line > "table_$tablesuffix"

Also it's better to stick to one thread for a topic instead of two

Author:  porchrat [ Tue Oct 21, 2008 5:45 am ]
Post subject: 

No worries sorted it out using awk.

Only took one line.

awk '/stopword$/{close(five".table");five=$5}{print > five".table" } ' $1

But thanks anyway, yours would've worked as well.

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group •