1

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
    You might try using `find` with a combination of bash parameter expansions. Something like `f=$(find . -name '*.datt') ; f="${f##*/}" ; echo "${f%%.*}"` – j_b Jun 21 '23 at 19:28
  • @j_b: thanks. this script worked. – EverLearner Jun 21 '23 at 19:31
  • You might also want to consider using [basename](https://man7.org/linux/man-pages/man1/basename.1.html). – DevSolar Jun 21 '23 at 20:21
  • See [I just assigned a variable, but echo $variable shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else). Your first echo is tricking you into believing that `myfile` contains `test.datt` but it really contains `*.datt`, then when you remove the extension you just get `*` which expands to all files in the directory. – tjm3772 Jun 21 '23 at 20:33

1 Answers1

1

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.
pjh
  • 6,388
  • 2
  • 16
  • 17