replace strings in array with bash
I need to work with bash only and im new to it
#!/opt/bin/bash
SAVEIFS=$I开发者_StackOverflowFS
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
Add this to the end of your script:
for i in ${!array[@]}; do
array[i]="${array[i]%%.???}"
done
Two tricks were used here:
- The list of an array indexes:
${!array[@]}
(see info) - 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
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[@]%.*}"
)
精彩评论