user3173191
user3173191

Reputation:

UNIX find and replace using execdir and bash

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?

Upvotes: 1

Views: 245

Answers (1)

that other guy
that other guy

Reputation: 123750

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 --^

Upvotes: 2

Related Questions