I’m just making my first attempts with awk and have one, maybe, simple question. I am trying to list a directory and extract some information from the listing based on a string. The bash script I’m trying is:
ls *.hdf > temporary.list
nom2=`awk 'BEGIN {FS = "." } ; { $1 ~ /'$year$month'/ } { print $2 }' temporary.list `
file=$year$month.$nom2.hdf
file2=$year$month.hdf
where year and month change in a for loop (1981 to 1985 and 01 to 12). The temporary.list file is composed of 12 lines like:
198201.s04m1pfv51-bsst.hdf
198202.s04m1pfv51-bsst.hdf
198203.s04m1pfv51-bsst.hdf
198204.s04m1pfv51-bsst.hdf
198205.s04m1pfv51-bsst.hdf
198206.s04m1pfv51-bsst.hdf
198207.s04m1pfv51-bsst.hdf
198208.s04m1pfv51-bsst.hdf
198209.s04m1pfv51-bsst.hdf
198210.s04m1pfv51-bsst.hdf
198211.s04m1pfv51-bsst.hdf
198212.s04m1pfv51-bsst.hdf
I want to select files depending on year-month. The problem is that my awk sentence does not seem to get different lines as different registers, I suppose. The output of the script is:
nom2 = h s04m1pfv51-bsst h s04m1pfv51-bsst h s04m1pfv51-bsst h
s04m1pfv51-bsst h s04m1pfv51-bsst h s04m1pfv51-bsst h s04m1pfv51-bsst
s04m1pfv51-bsst s04m1pfv51-bsst s04m1pfv51-bsst s04m1pfv51-bsst
s04m1pfv51-bsst
file = 198201.h s04m1pfv51-bsst h s04m1pfv51-bsst h
s04m1pfv51-bsst h s04m1pfv51-bsst h s04m1pfv51-bsst h s04m1pfv51-bsst
h s04m1pfv51-bsst s04m1pfv51-bsst s04m1pfv51-bsst s04m1pfv51-bsst
s04m1pfv51-bsst s04m1pfv51-bsst.hdf
file2= 198201.hdf
Maybe is some simple syntax error, any help would be appreciated.
Thanks
You need to give
awkthe variables you need it to know about.To pass a variable to
awk, use-vfor each one.awkvars can then be used directly, no$needed.as with
printthe space between them will be ignored, a real space would have to be quoted.So the way it is now, it checks if the first field (
$1) exactly matches (==) ‘y m‘ which is expanded to ‘${year}${month}‘. If the match happens then the 2nd field ($2) is printed.keep in mind that
awklogic blocks are in the formnote no curly braces around
conditionyou also don’t need
;between blocks, only between actions, but they don’t hurt either.so,
{ $1 ~ /'$year$month'/ }will do nothing the way it is written.having said all that, I would go with pure
Bashfor what you’re doing: