Search code examples
linuxbashcommand-line-interface

Move files if ID in CSV file


We have a directory with files in the following format.

[id].mp4

We also have a list of ID's in the form of a CSV file.

We need to move all files with the corresponding ID to a different directory.

Can someone please explain how to do this with a bash script?


Solution

  • it's easy, first of all extracts the IDs, and then moves the corresponding files to the desired directory.

    something like this :

    #!/bin/bash
    
    csv_file="path/to/ids.csv"
    source_dir="path/to/source"
    destination_dir="path/to/destination"
    
    while IFS=',' read -r id; do
      #to remove double quotes from the ID
      id=$(echo "$id" | tr -d '"')
      
      file="${source_dir}/${id}.mp4"
      if [[ -f "$file" ]]; then
        mv "$file" "$destination_dir"
        echo "Moved file $file to $destination_dir"
      else
        echo "File $file not found"
      fi
    done < "$csv_file"