List files in a directory without listing the ones in the current directory

findgreplssed

Say I have a file *.txt in a directory txtpath=/path/to/txt/.

I would like to list *.txt files in $txtpath from current directory (not $txtpath) without also listing the files in the current directory, as it happens if I execute ls *.txt $txtpath .

I manage to list the *.txt files only in $txtpath with this command: find $txtpath -name '*.txt' | sed 's/\// /g' | grep -o '[^ ]*$'

But maybe there is a more elegant solution?

Best Answer

Simply specify the full path along with the pattern:

ls -d -- "${txtpath}"/*.txt

Though in effect the listing is done by the shell globbing, ls ends up just printing the arguments that it receives from the shell. You might as well use printf here:

printf '%s\n' "${txtpath}"/*.txt

Which would give the same result except (in the shells that don't cancel commands upon non-matching globs) in the case where there's no non-hidden txt file in the directory.

Related Question