4

I need to work with bash only and im new to it

#!/opt/bin/bash
SAVEIFS=$IFS
IFS=$'\n'
array=($(mysql --host=xxxx --user=xxxx --password=xxxx -s -N -e 'use xbmc_video; SELECT strFilename FROM movie, files WHERE files.idFile=movie.idFile ORDER BY idMovie DESC LIMIT 10;'))

This produces an array of filenames with spaces within since im working on windows samba shares. Question is how can I delete last 4 symbols in every string to get rid of extensions without having to bother which ext is that I want to get pure file names

2 Answers 2

6

Add this to the end of your script:

for i in ${!array[@]}; do
    array[i]="${array[i]%%.???}"
done

Two tricks were used here:

  1. The list of an array indexes: ${!array[@]} (see info)
  2. The pattern cut-off from the end: "${array[i]%%.???}" (must be in double quotes because of the spaces in the file names) (see info)

To ensure (later when you use the array) that you get the whole name of the file use the following trick in the loop:

for file in "${array[@]}"; do  # the double-quotes are important
    echo "$file"
done

For more info see the bash hackers site and the bash manual

Sign up to request clarification or add additional context in comments.

2 Comments

thank You for that - I guess I still miss the whole concept tho now when filename got commas within hes name, the trick fails. Nothing happens to that filename
I've edited the pattern replacement method to 'cut the end counting from the end' (see wiki.bash-hackers.org/syntax/pe?s[]=replace#substring_removal)
1

I'll give you a couple of options. First, you could edit off the file extensions as part of the command that generates the array in the first place:

array=($(mysql --host=xxxx --user=xxxx --password=xxxx -s -N -e 'use xbmc_video; SELECT strFilename FROM movie, files WHERE files.idFile=movie.idFile ORDER BY idMovie DESC LIMIT 10;' | sed 's/[.]...$//'))

(note that this assumes 3-letter extensions. If you need to trim any-sized extensions, change the sed command to sed 's/[.].*$//')

Second, you can trim the extensions from the entire array like this:

trimmedarray=("${array[@]%.???}")

(again, this assumes 3-letter extensions; for any size, use "${array[@]%.*}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.