Unix - moving .txt files when corresponding .ctl files exist

Below is a sample script for moving .txt files from one directory to another only when a corresponding .ctl file exists for them.

This is a command line script. It can be customised for a shell script.

Requirements - 
Move .txt files from directory SRC_DIR to TGT_DIR only when a corresponding .ctl file exists.
The file name should follow the pattern ABC*.txt
Eg - SRC_DIR ls
ABC1.txt
ABC2.txt
ABC3.txt
ABC1.ctl
ABC3.CtL
ABC4.ctl

In this case only the below files would be moved to TGT_DIR -

ABC1.txt
ABC3.txt
ABC1.ctl
ABC3.CtL

As you can see the [.ctl] part is case insensitive.

Solution - 

for i in #SOURCE_DIR#/ABC*.[cC][tT][lL]; do [ -f "${i%%.[cC][tT][lL]}.txt" ]  &&  mv ${i%%.[cC][tT][lL]}.txt $i  #TGT_DIR#; done

How this works - 

1) The for loop keeps scanning for source files which meet the requirement criteria.
2) [cC][tT][lL] searches for the ctl extension in a case insensitive way.
3)Combining the -f (if file exists) and mv command with a && operator makes sure that the scond command executes only when the first command has executed successfully.
4) Rest are as per usual unix command and syntax.

Please let me know if you have any questions on this or if you have any alternate approaches.

Till then,
Keep coding !!!!!

Post a Comment

Previous Post Next Post

Contact Form