Search code examples
linuxbashrm

Command to delete multiple files


I'm a new student in programming and I'm stuck on a question, which is:

Enter a command to delete all files that have filename starting with logtest, except logtest itself (delete all files starting with 'logtest' followed by one or more characters.)

rm -r -- !(logtest.*) didn't work.


Solution

  • Your approach was not totally wrong. Since you're dealing with a list coming to STDIN and rm expects parameters, you need to use xargs.

    Another thing is that you have to escape a dot when you grep for a filename. Your Command should look sth. like this.:

    ls | grep -v 'logtest\.' | grep 'logtest' | xargs rm 
    

    Note that you do a doubled grep. The first one to exclude your logtest.* itself and the second to include your remaining files with logtest.