bash 用bash替换数组中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7483491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace strings in array with bash
提问by zero
I need to work with bash only and im new to it
我只需要使用 bash 并且我是新来的
#!/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
由于我正在处理 windows samba 共享,这会生成一个包含空格的文件名数组。问题是如何删除每个字符串中的最后 4 个符号以摆脱扩展名,而不必担心我想要获得纯文件名的扩展名
回答by Rajish
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 siteand the bash manual
回答by Gordon Davisson
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/[.].*$//')
(请注意,这假设是 3 个字母的扩展名。如果您需要修剪任何大小的扩展名,请将 sed 命令更改为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[@]%.*}")
(同样,这假设是 3 个字母的扩展名;对于任何大小,请使用"${array[@]%.*}")

