want to get last year and month from the file

Hi
I have files like

abc_cd_20110302_123423
abc_cd_ef_20110301_123423
abc_cd_ef_20110403_123423
abc_ef_20110401_123423

I want to extract the
the year and month associated with each file.
I tried

logfileyearmonth=`echo $logfile | awk -F_'{print $NF}'`

Any other way can I get the yearmonthdate from the file which is in bold.
This is basicaly the last second field.

Thanks and Regards
Dgmm

If "NF" is the last field, then "(NF-1)" is the second last field:

logfileyearmonth=$(awk -F_ '{print $(NF-1)}' $logfile)

I have one of the file as
acs_log_purge_20110517_234239
Got following error.

]+ + awk -F_ {print $(NF-1)} acs_log_purge_20110517_234239 
awk: input file "acs_log_purge_20110517_234239": The system cannot find the file specified. 

Sorry, I misread your question slightly.

logfileyearmonth=`echo $logfile | awk -F_ '{print $(NF-1)}'`

(I don't know where "$logfile" is set, and making no assumptions, $(NF-1) will give you the field you are looking for)

# Test, create some files:
echo "abc_cd_20110302_123423
abc_cd_ef_20110301_123423
abc_cd_ef_20110403_123423
abc_ef_20110401_123423" | xargs touch

$ ls * | awk -F_ '{print $(NF-1)}'
20110302
20110301
20110403
20110401

I am not looking from ls.
Here is my code and I want to fetch year and month from the file which I have alread read.

cd Log_dir
 
for f in *.log
do
  let  cnt="cnt + 1"
  logfilename=$f
  Log "Log file Name $logfilename"
  logfile=`basename $logfilename .log`
  Log "logfile without extension $logfile"
  logfiledate=$`awk -F_ '{print $(NF-1)}' $logfile`
  Log "logfiledate $logfiledate"
done
Log "Total file count $cnt"

The problem is I am not getting logfiledate.
Please let me know how can I extract this field. My datetime in file is last 15 characters. f_CCYYMMDD_HHMMSS.
Just want to get CCYYMM from the file.
Thanks and Regards\
Dgmm

If you have the logfile name already, then go back to what you had, and use $(NF-1) from the beginning:

...
logfiledate=$(echo $logfile | awk -F_ '{print $(NF-1)}')
...
cd Log_dir
 
for f in *.log
do
  let  cnt="cnt + 1"
  logfilename=$f
  Log "Log file Name $logfilename"
  logfile=${logfilename%.*}
  Log "logfile without extension $logfile"
  logfiledate=$(echo $logfile | awk -F_ '{print $(NF-1)}')
  Log "logfiledate $logfiledate"
done
Log "Total file count $cnt"
1 Like

Thank you.
This worked.