通过bash shell脚本,我试图从文件名中读取一个月

时间:2014-07-24 20:26:13

标签: bash

Nb:此问题在https://stackoverflow.com/questions/24919063/trying-to-pass-the-string-value-to-print

之后

通过bash shell脚本,我正在尝试读取文件名(FACT_PEOPLE_201401.txt)。

for File in `ls -1 ${OFSR_IN}/FACT_PEOPLE_*.txt
    do
         File_name=`basename ${File}`
         Ext_Year=`echo ${File_name} | cut -c 13-16`  #for YEAR
         Ext_Month=`echo ${File_name} | cut -c 17-18`  #for MONTH - trying to extract month

         echo ${EXT_Year}
         echo ${EXT_Month}
         EXT_YEARMTH_1=${Ext_Year}${var}${Ext_Month}  # concatenating year & month       

         echo "\$\$HR_YEARMONTH=${EXT_YEARMTH_1}" >> ${OFSR_CFG}/pmserver_OfsrHRSPeople05Loa.prm   # here outputing the value

我正在尝试在输出文件config.prm中打印yearmonth(EXT_YEARMTH_1)的值

echo "\$\$HR_YEARMONTH=${EXT_YEARMTH_1}" >> ${OFSR_CFG}/pmserver_OfsrHRSPeople05Loa.prm

但是我无法打印正确的年份,如2014/01。相反,我得到输出

$$HR_YEARMONTH=

我希望我的输出在文件名中没有引号

$InputFile_People=$PMRootDir\rlhrs\data\in\FACT_PEOPLE_201306.txt
$$HR_YEARMONTH=2014/01

1 个答案:

答案 0 :(得分:1)

此:

for file in FACT_PEOPLE*.txt
do
    sed 's:.*_\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\).txt:\1/\2:' <<< "$file"
done
输入

FACT_PEOPLE_201401.txt

将打印

2014/01

如果要将年份和月份分配给变量,可以使用:

for file in FACT_PEOPLE_*.txt
do
        read -r year month < <(sed 's:.*_\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\).txt:\1 \2:' <<< "$file")
        echo YEAR: $year
        echo MONTH: $month
done

将打印什么

YEAR: 2014
MONTH: 01