Score:3

How can I delete all files in a folder with names that longer than X?

ru flag

I have a folder with 1000s of files in that are named 23123 123r3883 3929388394j f38238d etc. I need to remove all the files that have a name length > 9. How can I do this?

hr flag
Does it have to be bash? zsh has some handy glob qualifiers for this kind of thing
cn flag
please do use google. https://superuser.com/a/702461/276585 and no I am not going to steal fossie's answer there :D
Score:4
hr flag

You can match filenames that consist of at least 10 characters using a simple glob expression ??????????*. So provided the number of files is not too long, you could use

echo rm -- ??????????*

For longer file lists, you could break the names up using xargs:

printf '%s\0' -- ??????????* | xargs -r0 echo rm

If you switch from bash to zsh, you could make use of glob qualifiers to test the length of each filename (passed via the REPLY variable). One advantage is that you can easily add other qualifiers like N (equivalent of the bash shell's nullglob) and . (which limits the results to plain files):

echo rm -- *(.Ne:'[[ $#REPLY -gt 9 ]]':)

or

print -rNC1 -- *(.Ne:'[[ $#REPLY -gt 9 ]]':) | xargs -r0 echo rm

To do the equivalent in bash would likely require a loop, like

for f in *; do
  [[ -f $f && $#f -gt 9 ]] && echo rm -- "$f"
done

Remove the echo once you are satisfied that the right files are being matched.

pLumo avatar
in flag
Or `find -maxdepth 1 -type f -name "?????????*" -delete`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.