0

I am new to bash scripting and need help:

I need to remove specific files from a directory . My goal is to find in each subdirectory a file called "filename.A" and remove all files that starts with "filename" with extension B, that is: "filename01.B" , "filename02.B" etc..

I tried:

B_folders="$(find /someparentdirectory -type d -name "*.B" | sed 's#  (.*\)/.*#\1#'|uniq)"
A_folders="$(find "$B_folders" -type f -name "*.A")"

for FILE in "$A_folders" ; do
   A="${file%.A}"
   find "$FILE" -name "$A*.B" -exec rm -f {}\;
done

Started to get problems when the directories name contained spaces.

Any suggestions for the right way to do it?

EDIT:

My goal is to find in each subdirectory (may have spaces in its name), files in the form: "filename.A"

if such files exists:

check if "filename*.B" exists And remove it, That is: remove: "filename01.B" , "filename02.B" etc..

2 Answers 2

2

In bash 4, it's simply

shopt -s globstar nullglob
for f in some_parent_directory/**/filename.A; do
    rm -f "${f%.A}"*.B
done
Sign up to request clarification or add additional context in comments.

4 Comments

it works, but in case there isn't a "filename*.B" it will try to remove it even though it doesn't exist. how can I avoid this?
I added the -f to suppress the error when the file does not exist.
If "some_parent_directory" is actually 2 or more directories path stored in a variable (output of a find command : folders="$(find /g -type d -name "jpegtest*")" , it wouldn't search all subdirectories of all the directories. what is missing?
Please open a new question for that.
0

If the space is the only issue you can modify the find inside the for as follows:

find "$FILE" -name "$A*.B" -print0 | xargs -0 rm

man find shows:

  -print0
          True; print the full file name on the standard output, followed by a null character (instead of the newline character that  -print  uses).   This  allows
          file  names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output.  This option corre-
          sponds to the -0 option of xargs.

and xarg's manual

  -0     Input  items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literal-
          ly).  Disables the end of file string, which is treated like any other argument.  Useful when input items might contain  white  space,  quote  marks,  or
          backslashes.  The GNU find -print0 option produces input suitable for this mode.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.