spoke
spoke

Reputation: 267

Match files names in bash

I have two files. The first contains the movie and the second the subtitle. First I take the movie file and I want to search in the same directory for the subtitle file. I know that I could do it with grep, but how can I make it compare the two files name, by taking into account only N letters, and it should not take into account the characters -, _, ..

I am new to bash and I still have some problems writing these commands. Can anyone help?

example: File 1: Avengers.avi

File 2: av-engers.sub

File 3: aveMgers.sub

Prefix should be 4 letters long => it will match file 1 and file 2 because if we exclude the - character they have at least the first 4 characters the same. File 3 doesn't respect this so file 1 and file 2 will be copied in a new Folder aven (the first 4 characters). This last part isin't so important.

Upvotes: 0

Views: 69

Answers (1)

Barmar
Barmar

Reputation: 782785

for avi in *.avi
do
    # remove punctuation characters
    aviPrefix="${avi//[-_.]//}"
    # get first 4 characters
    aviPrefix="${avi:0:4}"
    for sub in *.sub
    do
        subPrefix="${sub//[-_.]//}"
        subPrefix="${sub:0:4}"
        # Test if files have the same prefix
        if [[ $subPrefix = $aviPrefix ]]
        then
            if ! [[ -d "$aviPrefix" ]];
            then 
                mkdir "$aviPrefix"
                cp "$avi" "$aviPrefix"
            fi
            cp "$sub" "$aviPrefix"
        fi
    done
done

Upvotes: 1

Related Questions