Shell Scripting for moving files from source to target dir Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Shell Scripting for moving files from source to target dir without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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.

sourcedir=/some/dir
destdir=/some/other/dir

for csvfile in "$sourcedir"/*.csv; do
    txtfile="${csvfile%.csv}.txt"
    if [ -e "$txtfile" ]; then
        printf 'Will move %s to %sn' "$csvfile" "$destdir"
        # mv -i "$csvfile" "$destdir"
    fi
done

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.

We are here to answer your question about Shell Scripting for moving files from source to target dir - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji