Trying to write a shell script to move all the .csv files present in source location to target location. Condition is only those .csv files should be moved who have their corresponding .txt files.

Example: source:/home/source has abc.csv,abc.txt,def.csv,def.txt,efg.csv so based on condition only abc.csv,def.csv should move to destination dir and as efg.csv doesnt have it corresponding efg.txt file so it should not be moved to destination dir.


Loop over the csv files and test whether there's a txt file with the same filename stem. If there is, move the csv file.


for csvfile in "$sourcedir"/*.csv; do
    if [ -e "$txtfile" ]; then
        printf 'Will move %s to %s\n' "$csvfile" "$destdir"
        # mv -i "$csvfile" "$destdir"

The parameter expansion ${csvfile%.csv}.txt would take .csv off of the end of the current filename in $csvfile and replace that with .txt.

The mv command has been commented out for safety.

  • Hi Kusalananda, Thanks a lot for your valuable inputs.This has answered my problem. Could you please answer one more query: If my source directory is some sFTP server with credentials: username: xyz.com and pwd:achdvj%% and target directory is linux server again with username, pwd, servername and target path. Then how this could have been implemented with the above logic. – KAPZ Jul 9 '18 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.