0

I have the code below. If I want to loop through PKA1 through PKA24, how do i do that, without manually typing it all out

 cd PKA1/1keV/
    rm cascade.dump
 cd ../../

3 Answers 3

1

I'd consider using something like this

rm PKA{1..24}/1keV/cascade.dump
3
  • This is OK as long as you are using bash. Commented Jul 19, 2017 at 22:31
  • 1
    @Bob it's tagged bash Commented Jul 19, 2017 at 22:39
  • 1
    Good point! I always tend to go for more generic answers, I guess. Commented Jul 19, 2017 at 22:42
0

The first thing is that you don't have to be in a directory to remove the file, so you could just say:

rm PKA1/1keV/cascade.dump
rm PKA2/1keV/cascade.dump  

etc. However, a loop can be used:

for i in $(seq 24); do
   rm PKA$i/1keV/cascade.dump
done  

(the seq command generates the number 1 to 24 automatically)

2
  • Or just rm PKA{1..24}/1keV/cascade.dump. or find . -name cascade.dump -type f -delete. Commented Jul 19, 2017 at 22:28
  • The comment about bash also applies here. The find solution is a bit dangerous, as there might be other subdirectories containing cascade.dump that you don't want to delete. Commented Jul 19, 2017 at 22:32
0

'find' is your answer:

First use it with 'echo' to check out that everything will work correctly. I suppose that you don't care about the same filename in more PKA directories.

find PKA* -name "cascade.dump" -exec rm {} \;

Otherwise you have to fix the first pattern.

2
  • That will also hit directories such as PKA99 (if it exists) whereas the OP as specified only PKA1..PKA24. Your -exec rm{} \; kicks off an instance of rm for every file. While there are only 24 it's not a big deal but for a large number it files it could be. You'd be better with -delete if it exists for your find version, which doesn't fork any separate processes. Commented Jul 19, 2017 at 22:47
  • You are true. I warned him about more directories. Because he told about a dump file I supposed that he has more and he does not care; also I mention this. Commented Jul 19, 2017 at 22:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.