2

Let's say that I need to filter all my files' names that don't include special characters.

ASDA123fasf - would pass
asasdasd*dasd - wouldn't pass
  • 2
    What exactly are non-special characters? Only letters? Numbers? "Simple" symbols like minus or underscore? – Byte Commander May 19 '18 at 18:36
  • Yes, the regex should filter only files' names that have letters and digits in it – Anthino Russo May 19 '18 at 18:39
  • You could start by trying something like find FOLDER/ -iregex '.*/[a-z0-9.]*'. Note the beginning .*/ in the pattern, because -iregex matches against the whole path, not just the file name, and also that I added a . tot he allowed characters inside the square brackets, so that it still will match files with extensions. You might want to remove that one depending on your goals. The match is case-insensitive. – Byte Commander May 19 '18 at 18:49
  • No, they shouldn't @dsstorefile1 Anyway, is there a grep solution? #Byte Commander – Anthino Russo May 19 '18 at 18:52
  • 2
    What do you mean by "filter", exactly? Can you give a simple use case (i.e. what are you going to apply the expression to, and what are you going to do with the result)? – steeldriver May 19 '18 at 18:53
  • Already said. Imagine I do ls and I want to get only names of the folders with letters and digits. ASAS23123fasf would pass, 123123fasf would pass aswell but asdads&*!@213 shouldn't pass – Anthino Russo May 19 '18 at 19:01
  • Use find. The output of ls is meant for human eyes and not to be parsed. While you could theoretically tape something together like ls | grep -i '[a-z0-9.]*', that would be bad practice and not reliable for some cases. – Byte Commander May 19 '18 at 19:07
  • 1
    With bash extended globbing (shopt -s extglob - although it should be enabled by default) ls *([[:alnum:]]) will list files whose names are alphanumeric – steeldriver May 19 '18 at 19:10

1 Answers1

0

One of many alternatives would be find . -maxdepth 1 -iregex '.*/[a-z0-9.]*' -ls

If you think you may need to use this often, you could even create an alias to shorten the command:

Note: The below alias will only work in the current directory, although you could easily create a script that would parse a command line argument for the directory..

alias myls="find . -maxdepth 1 -iregex '.*/[a-z0-9.]*' -ls"

If you were to do that, every time you issued the command myls you'd get the desired output without all the extra typing. Lazy or efficient, you decide.

Sources: Byte Commander comment here

https://stackoverflow.com/questions/4509624/how-to-limit-depth-for-recursive-file-list - specifically this answer

man find

Elder Geek
  • 36,023
  • 25
  • 98
  • 183