1

I want to move a file to a folder based on its file extension. example: if the file is .csv,it should move to COMPLETED folder , if the file has any extension other any .csv then it should move to REGULAR folder.

Below is my shell script and its not working. Can you let me know what is the problem with it?

#!/bin/bash
cd /apps/int/apd/$1/work

if ls /apps/int/apd/$1/work/*.csv &> /dev/null; then
    mv *.csv /apps/int/apd/$1/COMPLETED
else
    /apps/int/apd/$1/Regular
fi

2 Answers 2

5

Why do you have to check the existence of *.csv files?

#!/bin/bash
cd /apps/int/apd/$1/work

mv *.csv /apps/int/apd/$1/COMPLETED 2>/dev/null
mv * /apps/int/apd/$1/Regular

Here first .csv files are moved to COMPLETED folder. Then rest of the files are moved to Regular folder.

I am assuming you have created COMPLETED and Regular folders.

Sign up to request clarification or add additional context in comments.

3 Comments

Checking for csv files before calling mv allows you to separate the two possible ways mv could fail: not being able to move the file literally named "*.csv", and not being able to move actual csv files.
But from the requirement, what i see is any file with extension .csv should be moved. So, even if the filename is literally "*.csv", i guess that should also be moved.
Most likely, though, is that there is no file named *.csv, but that is the name passed to mv by the shell, which will cause mv to fail. Since you silence the error message to avoid seeing that, you won't know if there was some other problem with the mv, like the directory COMPLETED not existing. It's better to test for the error conditions you can anticipate and show the messages for the errors you cannot. One possible consequence is that the first mv fails, then all the files are moved into Regular.
0

Change YOUR_PATH with your specific path and your path for /COMPLETED/ and /REGULAR/.

If I got what you wanted to explain i think your variables look like theese:

/YOUR_PATH/ = /apps/int/apd/$1/work
/COMPLETED/ = /apps/int/apd/$1/COMPLETED
/REGULAR/ = /apps/int/apd/$1/Regular    

You can try this. :)

#!/bin/bash

for filename in /YOUR_PATH/*;
do
    Path="$filename"
    extension="${filename##*.}"
    if [ "${extension}" = 'csv' ]; then
            mv $Path /COMPLETED/
    else
            mv $Path /REGULAR/
    fi
done

If you need anything pls leave a comment. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.