1

I have a list of directories that I want to go into and delete particular files. For example, the directory names I have are as below:

091513
090213
082612
071611
020908
011009
...
062308

Each of these directories has 4 files in them and the file names are:

dealer_score_01.txt
dealer_score_02.txt
dealer_score_03.txt
dealer_score_04.txt

I want to write a script that would go into each of these directories and delete:

dealer_score_01.txt
dealer_score_03.txt

Can someone please help me with that?

1
  • man find, read the exec and name parts
    – dawud
    Commented Sep 18, 2013 at 7:15

2 Answers 2

2

You don't have to go into each directory separately. Just pass the file names you want deleted to find and delete them with the -delete option.

find . -type f \
\( -name 'dealer_score_01.txt' -or -name 'dealer_score_03.txt' \) -delete

Leave out -delete to make sure you delete the right files.

4
  • Hi Slhck, Thanks for the reply. I want to delete these files only in certain directories.If i use the command above, it would delete these files in all the directories. Is there any way to delete only in few directories by specifying the directory names in which i want these files to be deleted?
    – user255223
    Commented Sep 18, 2013 at 8:55
  • 1
    You can just specify the directory names instead of . for the find command. For example find 091513 090213 -type f …
    – slhck
    Commented Sep 18, 2013 at 9:08
  • How many directories can I specify at a time in the find command? I have more than 200 directories that I want to do this with...
    – user255223
    Commented Sep 18, 2013 at 12:08
  • 1
    You can specify as many as you want. How do you get the list of directories in the first place? In a text file? From a command? Maybe you should clarify your question and tell us what exactly you need to do.
    – slhck
    Commented Sep 18, 2013 at 12:17
0

If you have a list of the directories already (as your comments suggest) you could do it with a loop. If the list of directories is, say, in dir_list, and assuming none of your directories contain new lines in their name:

while read -r dir; do
  rm -f "$dir"/dealer_score_0{1,3}.txt
done < dir_list

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .