检查文件是否具有适当的后缀bash
这是我写的检查文件是否具有适当的后缀bash,bash,Bash,这是我写的 function copyFile() { local source=$1 set -x for dictionary in $DICT_PATH; do dictname=$(basename $dictionary) dict_prefix=${dictname%%.*} TARGET="gs://bucket/files" gsutil cp -r $dictionary $TARGET
function copyFile() {
local source=$1
set -x
for dictionary in $DICT_PATH; do
dictname=$(basename $dictionary)
dict_prefix=${dictname%%.*}
TARGET="gs://bucket/files"
gsutil cp -r $dictionary $TARGET
done
}
function copyFile() {
local source=$1
set -x
for dictionary in $DICT_PATH; do
dictname=$(basename $dictionary)
if [[ ${dictname: -5} == ".json" ]] || [[ ${dictname: -5} == ".xml" ]] ; then
dict_prefix=${dictname%%.*}
TARGET="gs://bucket/files"
gsutil cp -r $dictionary $TARGET
fi
done
}
我想添加一个条件,只复制终止为.json或.xml的文件
这是我写的
function copyFile() {
local source=$1
set -x
for dictionary in $DICT_PATH; do
dictname=$(basename $dictionary)
dict_prefix=${dictname%%.*}
TARGET="gs://bucket/files"
gsutil cp -r $dictionary $TARGET
done
}
function copyFile() {
local source=$1
set -x
for dictionary in $DICT_PATH; do
dictname=$(basename $dictionary)
if [[ ${dictname: -5} == ".json" ]] || [[ ${dictname: -5} == ".xml" ]] ; then
dict_prefix=${dictname%%.*}
TARGET="gs://bucket/files"
gsutil cp -r $dictionary $TARGET
fi
done
}
但这不起作用。您知道如何解决此问题吗。您可以将文件扩展名提取为
${filename}.*.}
这应该会产生如下的结果:
ext=${dictname#*.}
if [[ $ext == 'json']] || [[ $ext == 'xml' ]]; then
# code
fi
或者,使用正则表达式
if [[ $dictname =~ (json|xml)$ ]]; then
# code
fi
试试这个:
filetype=${dictionary##*.}
if [[ "$filetype" == "json" ]] || [[ "$filetype" == "xml" ]]; then
echo YES
fi
xml
比json
短,因此后缀太长,无法与.xml
进行比较
# -4, not -5
if [[ ${dictname: -5} == ".json" ]] || [[ ${dictname: -4} == ".xml" ]] ; then
您可以使用更简单的模式匹配工具[…]
来避免这个错误
if [[ $dictname = *.json || $dictname = *.xml ]]; then
甚至是POSIX兼容的案例
语句:
case $dictname in
*.json|*.xml)
dict_prefix=${dictname%%.*}
TARGET="gs://bucket/files"
gsutil cp -r "$dictionary" "$TARGET"
;;
sac
模式匹配会更简单:
如果[[$dictname=*.json | |$dictname=*.xml]];然后
。这将防止在表示-4
时使用-5
的可能性,就像您的xml
检查一样。