Deleting files from a directory based on search


Results 1 to 2 of 2

Thread: Deleting files from a directory based on search

  1. #1
    Join Date
    Sep 2000
    Posts
    1

    Deleting files from a directory based on search

    I need to delete files from a directory based on a search string. I tried:
    grep -iL include * | rm -f
    ("include" is the string I was looking for)
    This did not delete the files. The grep command alone found the correct files, but I can't pipe the results to the remove command.
    Can anyone help me complete this task? Am I taking the wrong approach, or can I use the rm command on the results of a grep?

  2. #2
    Join Date
    Sep 1999
    Location
    Cambridge, UK
    Posts
    509
    One way would be:

    Code:
    for i in *; do
      grep include $i >/dev/null && rm -f $i
    done
    I'm assuming you mean that the string "include" has to be in the file and not part of the file's name. The way you tried could work. You are almost there. If you can get the write files in a list you could use xargs. xargs takes a list of stuff from standard input and uses the list as the arguments to a command. Silly example, because I can't think of a way to do exactly what you wanted that's better than the one I propose above):

    Code:
    /bin/ls -w1 | xargs echo rm -f
    I find it's a good idea to test things like this with a judiciously placed echo! The full path to ls is to account for the fact that your shell may have aliased ls to 'ls --classify', which would append stars to executable files' names. Plus when you're happy you need only add a "| /bin/bash" to the end to actually go and do it!

    Incidentally there is another way to do it. It's pointless in this case but the general idea can be helpful. First write a script that expects a filename as an argument and does what you want to that file:

    Code:
    #!/bin/bash
    
    if [ $# = 0 ]; then
      echo usage: thescript filename
      exit
    fi
    
    grep include "$1" >/dev/null && rm -f "$1"
    Then run the following:

    Code:
    find /path/to/files -type f -exec thescript {} \;
    Yes you need the backslash, yes you need the semicolon, yes you need the space after the curly brackets.

    Happy hacking.

    [This message has been edited by furrycat (edited 09-25-2000).]

    [This message has been edited by furrycat (edited 09-25-2000).]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •