Shell Scripting for moving files from source to target dir

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 %sn' "$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.

Leave a Reply

Your email address will not be published. Required fields are marked *