Using AWK in a for loop

Hello,

I am trying to use AWK to print only the first field of numerous text files, and then overwrite these files. They are of the format 1*2,3,4,5. I have tried the following code (using tcsh):

 foreach f (file1 file2 file3)
cat $f | awk -F'*' '{print $1}' > $f
end

However, I get very inconsistent results each time I run this script. I have tried creating a tmp directory where I run the above command on a clean set of the files. But, sometimes it returns empty files, whereas other times it runs fine for all the files. Any ideas on what is going on here, or if there is a better way to get awk to do what I want?

On a side note, I have tried a similar method using cut:

 foreach f (file1 file2 file3)
cat $f | cut -d'*' -f1 > $f
end

but I get the same inconsistencies.

Thank you for your help,

-Jahn

The below line should be re-written..

cat $f | awk -F'*' '{print $1}' > $f

Try:

awk -F'*' '{print $1}' $f > _temp
mv ${_temp} $f

I'd personally get rid of the brackets around the foreach, but i dont know tcsh so it may be a requirement. It should work doing

 for file in file1 file2 file3 ; do awk -F'*' '{print $1}' < $file > $file ; done  

???

Here is what worked for me:

 foreach f (*)
awk -F'*' '{print $1}' $f > {$f}_temp
mv {$f}_temp $f
end

I have tried using the "awk code < file > newfile" redirection before, but I always end up with an empty newfile.

Thanks again for your help, guys!

sed 's/\*.*//' deletes everything from first * on lines :wink: