Home > Net >  Command to delete multiple files
Command to delete multiple files

Time:09-21

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.

CodePudding user response:

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

rm logtest?*

? matches a single character. * matches 0 or more. Combine them to match 1 or more characters.

Or if you mean all such files, not just ones in a particular directory...

find / -name "logtest?*" -exec rm \{\}  

CodePudding user response:

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.

CodePudding user response:

Something like this should work:

for file in *; do
    # Ensure that the file is a file and not a directory.
    [ -f "$file" ] && {
        if printf "%s" "$file" | grep "^logtest." > /dev/null; then
            rm -f "$file"
        fi
    }
done

This doesn't parse the output of ls, ensures that the file is actually a file and works with spaces aswell (names like "logtest ").

'^' means to match the start of the string so that stuff like "test_logtest" won't be matched, and the '.' at the end ensures that there are characters after the match. > /dev/null stands for redirecting the output of the grep command to /dev/null (All content sent there is discarded), which basically hides the grep matches from showing up in the output.

  • Related