3

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?

5

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.

  • actually, your solution does not work for me, ls: cannot access ${txtpath}*.txt: No such file or directory (I run your command with no slash because already included in my variable). But an even simpler solution works: just ls $txtpath*.txt - thanks for the hint – aechchiki Aug 17 '17 at 8:35
  • Ah yes, sorry, I got the quoting wrong; see my updated answer. – Stephen Kitt Aug 17 '17 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.