user3290216
user3290216

Reputation: 35

append date time stamp issue to filename in unix script

I have bunch of files that are generated by legacy system and the requirment is to rename the files to long description (something business users can understand).

Sample file name: bususrapp.O16200.L1686.1201201304590298

RptList: bususrapp Billing file for app user

when the system generates a file 'bususrapp' file, this will be translated to 'Billing file for app user' and the final output need to be something like "Billing file for app user.1201201304590298.txt"

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

The last qualifier in the sample file is my date&time stamp. I need to cut/copy and append it to the new long description file name. "Billing file for app user.1201201304590298.txt"

Please suggest how to achive this.

Upvotes: 2

Views: 774

Answers (2)

n0741337
n0741337

Reputation: 2504

Give your input file, this awk will make your desired output filename:

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

Use FS to do all of the hard work and then print the fields the fields out in your specified order.


Here's a more complete answer:

# 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

Just a different style. @EtanReisner 's answer is cleaner. Since I don't script in bash, this is what I would have tried.

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 80931

I believe the following will do what you want.

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

Upvotes: 2

Related Questions