在unix脚本中将日期时间戳问题附加到文件名

时间:2014-04-30 15:42:04

标签: shell unix awk

我有遗留系统生成的大量文件,而且要求将文件重命名为长描述(业务用户可以理解)。

示例文件名:bususrapp.O16200.L1686.1201201304590298

RptList:bususrapp Billing file for app user

当系统生成文件' bususrapp'文件,这将被翻译为“用户”的“结算文件”。最终的输出需要 类似" app app的结算文件.1201201304590298.txt "

for i in `ls * `;  do j=`grep $i /tmp/Rptlist | awk '{print $2 $3 $4 $5} ;'` mv $i $j;  done

示例文件中的最后一个限定符是我的日期和时间戳。我需要剪切/复制并将其附加到新的长​​描述文件名。 " 应用用户的结算文件.1201201304590298.txt "

请建议如何实现这一点。

2 个答案:

答案 0 :(得分:2)

给你的输入文件,这个awk会产生你想要的输出文件名:

echo "bususrapp.O16200.L1686.1201201304590298 RptList: bususrapp Billing file for app user" | awk -F"[.]| RptList| bususrapp " '{print $NF"." $4 ".txt"}'
Billing file for app user.1201201304590298.txt

使用FS执行所有艰苦工作,然后按指定的顺序打印字段。


这是一个更完整的答案:

# use find instead of ls, pointing to files only
find /tmp/Rptlist -name "bususrapp*" -type f -print |
awk -F/ '
    {
    # rebuild the path which was split up by FS
    for(i=1;i<NF;i++) path = path $i"/"
    fname=$NF

    # split up the file name for recombination
    c=split(fname, a, "[.]| RptList:| bususrapp ")

    # output 2 arguments the "/original/file/path" "/new/file/path"
    printf( "\"%s%s\" \"%s%s.%s.txt\"\n", path, fname, path, a[c], a[4] )
    path=""
    }' |
# use xargs to feed those two arguments to mv for the copy
xargs -n2 mv

只是一种不同的风格。 @EtanReisner的回答更清晰。因为我不用bash编写脚本,所以我会尝试这样做。

答案 1 :(得分:2)

我相信以下内容会做你想要的。

for file in *; do
    # Drop everything up to the last .
    stamp=${fname##*.};

    # Drop everything after the first period.
    name=${fname%%.*}

    # Find the matching line in RptList.
    line=$(grep "$name" RptList)
    # Drop the first (space separated) field.
    line=${line#* }

    outfile="$line.$stamp.txt"

    mv $file $outfile;
done
相关问题