Home > Enterprise >  how to transfer file using bash script datewise?
how to transfer file using bash script datewise?

Time:04-06

There are two types file.

  1. Book1_20190715_1A.gz,

  2. Book1_20190715A.gz,

  3. Book2_20190716_1A.gz,

  4. Book2_20190716A.gz

    Here, 2019 is year 07 is month & 15 is date also 16. Also here is two type file _1A & A.

    Need to Transfer Date-wise in Folder. Also Need to transfer different folder for different type file like _1A & A

If I grep like *_1A then it transfer _1A folder But if *A then it transfer A also _1A.

What I do now. Please Help me.

CodePudding user response:

Your question is not very clear, but this is what I think you are looking for:

#!/bin/bash

find . -type f -name "Book*" -print0 | while IFS= read -r -d '' file
do
    # Remove "Book1_"
    tempdirname=${file#*_}
    # Remove ".gz"
    dirname=${tempdirname%\.*}
    echo "$dirname"
    if [[ ! -d "$dirname" ]]
    then
        mkdir "$dirname"
    fi
    /bin/mv "$file" "$dirname"
done
  • the find lists all files named Book* and sends that list to a while loop.
  • from the filename, extract the directory name using variable expansion. First remove "Book1_", then remove ".gz". This leaves you with the date, and the "_1A" portion, if it is there.
  • then create the directory if it does not already exist.
  • move the file to the directory.

CodePudding user response:

You can move the *_1A.gz files first:

mv ./*_1A.gz dir_1A/
mv ./*A.gz dirA/

update:

If you prefer, you can make the globs a little more specific:

mv ./*_????????A.gz dirA/
mv ./*_????????_1A.gz dir_1A/

note: in globbing, ? means any character

Or more accurate but longer:

d='[[:digit:]]'
mv ./*_$d$d$d$d$d$d$d${d}A.gz dirA/
mv ./*_$d$d$d$d$d$d$d${d}_1A.gz dir_1A/
  • Related