4 ms·
Sometimes I want all filenames from a subdirectory, without the subdirectory name. I can do (ignoring parsing issues): for name in $(cd subdir; ls); do ec
by CJefferson 2y ago
Sometimes I want all filenames from a subdirectory, without the subdirectory name.
I can do (ignoring parsing issues):
for name in $(cd subdir; ls); do echo "$name"; done
This isn't easy to do with globbing (as far as I know)
- rascul 2y agoOne alternative: for name in subdir/*; do basename "$name"; done
- Izkata 2y agoAlso since subdir is hardcoded, you can reliably type it a second time to chop off however much of the start you want: for name in subdir/subsubdir/*; do echo "${name#subdir/}" # subsubdir/foo done
- xolox 2y agoNote this string replacement is not anchored (right?) which can end up biting you badly (depending on circumstances of course).
- chuckadams 2y agoIt's anchored on the left. ${name#subdir/} will turn 'subdir/abc' into 'abc', but will not touch foo/subdir/bar. I don't think bash even has syntax to replace in the middle of an expansion, I always pull out sed for that.
- xolox 2y agoThanks for clarifying, I learned something new today! Edit: It turns out that Bash does substitutions in the middle of strings using the ${string/substring/replacement} and ${string//substring/replacement} syntax, for more details see https://tldp.org/LDP/abs/html/string-manipulation.html https://tldp.org/LDP/abs/html/string-manipulation.html
- silvestrov 2y agoI'd really like if the "find" command supported this much easier, so if I write find some/dir/here -name '*.gz' then I could get the filenames without the "some/dir/here" prefix. It would also be nice if "find" (and "stat") could output the full info for a file in JSON format so I could use "jq" to filter and extract the needed info safely instead of having to split whitespace seperated columns.
- ykonstant 2y agoWhy would you do this work when stat (and GNU find) can `printf` the exact needed information without any parsing?
- deleted 2y ago[deleted]
- silvestrov 2y agoIf I need filesize and filename then I still need to parse a filename that might contain all kinds of weird ascii control characters or weird unicode. JSON makes that a lot less fragile.
- ykonstant 2y agoI don't get it; I need a concrete example.
- williamcotton 2y agoWhat about: find . -name '*.hs' -exec basename {} \;
- rascul 2y agoYou could get mixed up here because find is recursive by default and basename won't show that files might be in different subdirectories.
- genrilz 2y ago
- hawski 2y agoIf you are gonna do a subshell (cd subdir; ls) you can wrap the whole loop: (cd subdir for name in *; do echo "$name" done) But I prefer: for name in subdir/*; do name="${name#*/}" echo "$name" done
- chasil 2y agoThis is really easy to do with a shell pattern. $ x=/some/really/long/path/to/my/file.txt $ echo "${x##*/}" file.txt