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.