1

I am new to scripting and have a requirement where I need to change the special characters from file and replace with some other character.

Below is the file name where I have to replace the ? by _.

file - 21041159?74DECL?ARAÇÃO14581?5904289?6770700.pdf

result - 21041159_74DECL_ARAÇÃO14581_5904289_6770700.pdf

find . -depth -name '*\?*' -type f -execdir bash -c 'mv "$1" "${1/\?/_}"' -- {} \;

The above script changes the first occurrence of question mark to underscore but not from complete file name.

Please suggest what can be done?

1
  • Take a look at rename command and its regex feature. Commented Jun 23, 2016 at 18:33

1 Answer 1

2

A simplified version of your question is:

I can replace the first occurrence of a string in a bash variable with ${var/foo/bar}.

How can I replace all occurrences?

And the answer is to use double slash: ${var//foo/bar}.

In context, it would be:

find . -depth -name '*\?*' -type f -execdir bash -c 'mv "$1" "${1//\?/_}"' -- {} \;
                                                        # Here --^
Sign up to request clarification or add additional context in comments.

1 Comment

Why did you take the wildcards out of the -name option?

Your Answer

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