Home > Enterprise >  find with regular expression to replace file content
find with regular expression to replace file content

Time:09-28

I would like to replace recursively (in a project directory) the word 'javax' with 'jakarta'. That works for files ending in "java":

find . -name '*.java' | xargs sed -i 's/javax/jakarta/g'

I'd need to do the same also for XML files. To use a single command, I've tried modifying the find expression as follows:

find . -regex '^.*\.(java|xml)$'

However, no files are found. I've tried as well with:

find . -regex '.*/^.*\.(java|xml)$'

But still nothing. Can you help me to rewrite the finder expression to use multiple files suffixes? Thanks

CodePudding user response:

You can still use -name multiple times to match multiple pattern:

find . \( -name '*.java' -o -name '*.xml' \) -print0 |
xargs -0 sed -i 's/javax/jakarta/g'

If you want to use -regex then you should also use -regexrtype option for extended regex matching:

find . -regextype awk -regex '. \.(java|xml)$' -print0 |
xargs -0 sed -i 's/javax/jakarta/g'

Take note of -print0 and xargs -0 options to take care of file names with special characters.

  • Related