Hey everyone! I'm trying to understand how the `rm` command works. When I run `rm any-word*.any-ext`, it seems to delete files like `screen.jpg` and `screen01.jpg`. I want to know why it does this and how I can modify the command to avoid deleting `screen.jpg` while still removing `screen01.jpg` and other similar files. Thanks for your help!
7 Answers
You can also use `rm screen[0-9]*.jpg` to specifically target files with numbers in them while keeping `screen.jpg` safe from deletion.
When you're uncertain, you might want to swap `rm` with `echo`. This way, the shell will show you what files would be deleted without actually doing it. Also, you can use `ctrl+x *` to expand wildcards in bash and see what's being matched before executing commands.
To ensure you don't delete `screen.jpg`, you can use `rm screen?*.jpg`. The `?` matches exactly one character, which means it won't touch `screen.jpg`. If you need to delete only files with characters after 'screen', this is a perfect solution.
Ah, perfect! Thanks a lot!
If you need to delete `screen.jpg` precisely, you can refer to it as `screen.jpg`.
The `*` wildcard matches zero or more characters, so `screen*.jpg` will include `screen.jpg` since there are zero characters between `screen` and `.jpg`. If you want to exclude `screen.jpg`, use `screen?*.jpg`, which requires at least one character in between.
Got it, thanks for clearing that up!
You could use `ls | grep -e 'screen.+.jpg'` along with `rm`, but be careful with parsing the output of `ls` since whitespace can mess things up. It's typically better to use the `?*` pattern instead.
Using the `find` command might be helpful as well. You could do something like `find . -type f -regex '.*screen.+.jpg' -exec rm {} ;` to remove only the intended files without touching `screen.jpg`. Or simply use `find . -type f -regex '.*screen.+.jpg' -delete`.
That works too, thanks!