英文:
Filename root not correctly extracted
问题
# 目标文件夹中的目标文件 >> test.datt
myfile=*.datt
echo $myfile
echo
root="${myfile%.datt}"
echo $root
我的输出
test.datt
temp test.datt testroot
期望的输出
test
英文:
I would like to extract the filename (root) from a file with specific extension (.datt). This file is the only single file in my directory but could change its root name but extension remains fixed; therefore I need to use a "wildcard" to capture the name. Here is my little script that incorrectly outputs all the files. Appreciate your help.
# Target file in the folder >> test.datt
myfile=*.datt
echo $myfile
echo
root="${myfile%.datt}"
echo $root
My output
test.datt
temp test.datt testroot
Expected output
test
答案1
得分: 1
尝试使用 Shellcheck 清理的代码:
#! /bin/bash -p
myfiles=( *.datt )
echo "${myfiles[0]}"
echo
root=${myfiles[0]%.datt}
echo "$root"
- 问题中的输出是因为
echo $myfile等同于echo *.datt,$root的值是(字面上的)*,而echo $root等同于echo *。 - 使用
myfiles=( *.datt ),数组myfiles填充了与*.datt匹配的文件列表(预期只有一个)。 - 有关 Bash 数组的良好信息,请参阅 BashGuide/Arrays - Greg's Wiki。
英文:
Try this Shellcheck-clean code:
#! /bin/bash -p
myfiles=( *.datt )
echo "${myfiles[0]}"
echo
root=${myfiles[0]%.datt}
echo "$root"
- The output in the question occurs because
echo $myfileis equivalent toecho *.datt,$roothas the value (literal)*, andecho $rootis equivalent toecho *. - With
myfiles=( *.datt )the arraymyfilesis populated with the list of files that match*.datt(expected to be exactly one). - See BashGuide/Arrays - Greg's Wiki for good information about Bash arrays.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论