I am trying to output ‘awk’ result to file in my script, with no success.
Using ‘>’ does not work, why?
for a in $(find $OUPUT_DIR/ -maxdepth 1 -mindepth 1 -type d -printf "%P\n")
do
echo $a is a directory
awk -F, '{ if ($10 == '"$a"') print $0 }' $OUPUT_DIR/CDRNOutput_${CDR_DATE}.csv > $OUPUT_DIR/$a/CDR-${CDR_DATE}.csv
done
Output redirection is generally a feature of the shell you’re working with and, given how much use it gets, I’d be pretty amazed if you’d found a bug in it 🙂
Are you sure you’re not trying to do redirection with
awkitself rather than the shell?What happens when you do:
Update:
If this is your code as stated, it’s because the
$ais not being expanded by your shell script since theawkcommand is within single quotes.What I tend to do is pass in specific values to
awkusing the-voption, something like (in your case):Then the variables become first-class
awkcitizens without having to worry about who’s doing the expansion.Further update:
I’m standing behind my original advice. There’s something definitely screwy with the method chosen.
I have a directory in my home directory called XpVm (among others) and I’ve created the file
CDRNOutput_X.csvcontaining the single line:When I execute:
(I’ve stripped out directories starting with
.since they were causing another problem), I get this output:which is clearly not what is expected. However, when I use the
-voption toawkas I originally suggested, the command:(the only difference being the changes to
a), I get:which is correct.
Final update (hopefully):
I think I have the problem solved. I’m on a different machine now (so the directory names are simply
tmpandtmp2) and, when I run the original script:with a modified
CDRNOutput_X.csvcontainingtmpinstead ofXpVm, I get:That’s because the
ifstatement is being seen byawkas:(without quotes, since the quotes are actually outside the
awkstring being used to surround the directory name). This will test$10for equality against theawkvariable calledtmprather than the actual string"tmp". What you need is to make sure that the quotes are inside theawkscript, like:and you can do this with the following script (only the
ifline has changed):Note that the double quotes are duplicated. I’ve still kept the double quotes immediately around
$ain case someone’s committed the heinous crime of creating a file with a space in it 🙂Running that script produces:
which is what I think you were aiming for.
So, the upshot is, if you don’t want to use
awkvariables, you can just change your awk string from:to:
and it should function okay.