Need help in sorting the file and putting to a different folder

Hi,

I am new to unix. Kindly help me on this.

My requirement is as below:

I have a path temp/input , temp/CL and temp/CM

I have files in temp/input as below (dates in YYYYMMDDHHMISS)

  NMP1515O.CL.20181026111213
  NMP1515O.CM.20181025111213
  NMP1515O.CM.20181024111213
  NMP1515O.CL.20181023111213 

Basically I need to sort on basis of CL and timestamp. Similarly for CM and timestamp. Move only one file from CL and CM to relevant folders i.e temp/CL and temp/CM ***

Before moving the file from temp/input to temp/CL, we need to check if there is any file in the folder temp/CL. If there is file already in temp/CL, then we should not move from temp/input to temp/CL. File should be moved only when temp/CL is empty.

Same way we need to follow for CM.

Could you kindly help.

Thank you,
Priya

Let me see if I have this straight. You have file names in temp/input like temp/input/NMP1515O.CL.20181026111213, temp/input/NMP1515O.CM.20181025111213, etc, which you need to process in order of date by sorting into temp/CM and temp/CL. Only move a file when these folders are empty (implying the files we move in there will also disappear automatically).

Have I got that right?

If I do understand it, then maybe:

ls temp/input | sort -t. -k 3,3 | while IFS="." read NMP TYPE DATE
do
        case "$TYPE" in
        CL) ;; CM) ;; *) echo "Wrong type $TYPE" >&2 ; exit 1 ;;
        esac

        while [ "$(ls "temp/$TYPE" | wc -l)" -ne 0 ]
        do
                sleep 0.1 # Some systems can't sleep fractional seconds
        done

        echo "Moving $NMP.$TYPE.$DATE into temp/$TYPE" >&2
        echo mv "temp/input/$NMP.$TYPE.$DATE" "temp/$TYPE"
done

Let me paraphrase your request:
Move exactly one "CM" and one "CL" file to the respective directory (as, once a file has been moved, the directory is not empty any more). You did not specify anything about a sort order. How about

if ! ls temp/CM/* &>/dev/null ; then  echo mv -v $(ls -rt temp/input/*CM* | head -1) temp/CM; fi 
if ! ls temp/CL/* &>/dev/null ; then  echo mv -v $(ls -rt temp/input/*CL* | head -1) temp/CL; fi 


You might want to loop through all file types in a for loop.

Thank you for your reply. I am writing the script. You have been very helpful :slight_smile: