简体   繁体   中英

Get the full path of the only file in a directory

I have a directory with a single file. The name of the file is randomized, but the extension is fixed.

myDirectory
|----file12321.txt

Is there a one-line way to extract the full path of that file?

MY_FILE=myDirectory/*.txt

Current output:

/home/me/myDirectory/*.txt

Expected:

/home/me/myDirectory/file12321.txt

Use readlink to get canonized path.

MY_FILE=$(readlink -f myDirectory/*.txt)

If you want only myDirectory/file12321.txt part you could run a command that will let shell expand * , like:

MY_FILE=$(printf "%s\n" myDirectory/*.txt)

If it's certain that there is exactly one file, you can just use an array:

MY_FILE=( /home/me/myDirectory/*.txt )

Filename expansion takes place inside an array definition but not when setting the value of a normal variable. And you can just use the array like a normal variable, as that will provide the value of the first element:

$ foo=(1 2 3)
$ echo "$foo"
1
MY_FILE=$(pwd)/$(ls myDirectory/*.txt)
# $MYFILE == /home/me/myDirectory/file12321.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM