文件名根目录未正确提取。

huangapple go评论66阅读模式
英文:

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 $myfile is equivalent to echo *.datt, $root has the value (literal) *, and echo $root is equivalent to echo *.
  • With myfiles=( *.datt ) the array myfiles is 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.

huangapple
  • 本文由 发表于 2023年6月22日 03:02:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定