Reputation: 11
I need to loop through all the files in the same directory, and IF a specific line "File needs to be deleted" exists within any of the files within that directory, delete those files only. How would it work from the command line please?
For example, the directory contains file1, file2, file3 and so on for 1000's of files. Each file has 10,000 rows of strings. If any file contains the string"File needs to be deleted", delete those files, but don't delete the files that do not contain that string.
I was going along the lines of
for each file the directory; do
if [ row text == "File needs to be deleted" ]; then
delete file
fi
done
Upvotes: 0
Views: 145
Reputation: 4324
Simple bash example:
#!/bin/bash
# Get the running script name
running_script=$(realpath $0 | awk -F '/' '{ print $NF }')
# Loop throw all files in the current directory
for file in *; do
# If the filename is the same as the running script pass it.
[ "$file" == "$running_script" ] && continue
# If "File needs to be deleted" exists in the file delete the file.
grep -q "File needs to be deleted" "$file" && rm "$file"
done
Upvotes: 1
Reputation: 203975
grep -d skip -lF 'File needs to be deleted' file* | xargs echo rm --
If you only have files, no directories, in your current directory then you can just remove -d skip
. If your version of grep
doesn't have -d
but your directory does contain sub-directories then:
find . -maxdepth 1 -type f -exec grep -lF 'File needs to be deleted' {} + | xargs echo rm --
Remove the echo
once you've tested and are happy that it's going to remove the files you expect.
Upvotes: 1