8

I've accidentally redirected the output of a CSV file to my directory. How can I rm only the files that start with a number, and leave the files that start with a letter intact?

mymachine$ ls
71.24         README.md        30            4.29
8             filter.sh        42.81         5.58         
8.36          purchases.csv    1,208.8       100          
16.7          2.56             21.78         269.96        
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
spuder
  • 18,053

2 Answers2

18

Something like this should do it:

$ rm [0-9]*

Remember you can always use echo with any globbing arguments prior to letting rm run with them.

$ echo [0-9]*
100 1,208.8 16.7 21.78 2.56 269.96 30 42.81 4.29 5.58 71.24 8 8.36

After running the rm command above:

$ ls
filter.sh  purchases.csv  README.md
slm
  • 369,824
0

In this case you can also easily use find combined with the -regex and -delete options.

In the folder, first test your file selection:

$ find . -regex "[^/]+/.*[0-9]+"

Then add the -delete option:

$ find . -regex "[^/]+/.*[0-9]+" -delete

Your files are now deleted:

$ ls
filter.sh  purchases.csv  README.md

Always check your selection first, since using the [^/]+/.*[0-9]+ regular expression will select any file containing a number at the end (e.g. md5 or hdf5).

Please note that find automatically process subdirectories as well. If you don't want this add -maxdepth 1 before the regular expression.

For OS X add the -E option.

ganzpopp
  • 101
  • This answer would be much better if you [edit] it so that the regex starts with ^[0-9] to explicitly match filenames beginning with a digit (as per the question). – Anthony Geoghegan Jan 16 '17 at 09:43
  • The problem is that find adds the relative path to the output, so in this case a ./, so that wouldn't work. – ganzpopp Jan 16 '17 at 09:45
  • That would remove files whose name ends in at least one digit (equivalent to the standard -name '*[0-9]') which is not what is being asked for here. That would also look for those files in subdirectories which is not asked for either. – Stéphane Chazelas Jan 16 '17 at 09:52
  • That's what I indicated in my answer already. – ganzpopp Jan 16 '17 at 09:56
  • But you're right about the subdirectories, I added it to my answer. – ganzpopp Jan 16 '17 at 10:02
  • I forgot about the leading slash but ^\./[0-9].* would work. I think using a regex makes the command more complicated than it needs to be. Using -name with a shell globbing pattern should be sufficient, e.g., find . -name '[0-9]*'. The advantage of using find over slm’s excellent answer is that it could be used recursively (though that isn’t relevant to this specific question). – Anthony Geoghegan Jan 16 '17 at 10:03