Home > database >  Replace word in package names and variables in code
Replace word in package names and variables in code

Time:12-05

In my android project I got very intericting task My company wants to hide all mintions about her in code (variables names, packages and etc) But only for one flavour, so I cannot do it once for all project.

My first idea, was writing a simple gradle task, that will replace all strings that fit in code, but in this case package names will remain unchanged.

Secondly, since we have ci on Jenkins, I thought about jenkins script, that will rename all files and its content, if it has keyword. But this solution looks very bulky for me.

Maybe there is another, elegant way?

CodePudding user response:

Replacing the package name blindly seems a bit risky, as it could replace other overlapping strings as well, which may lead to various issues. Assuming your package name is unique and you don't have any overlapping names, you can use bash to achieve this.

sh '''
grep -rl ${PACKAGE_NAME_TO_REPLACE} ${DESTINATION_DIR} | xargs sed -i "s&${PACKAGE_NAME_TO_REPLACE}&${PACKAGE_NAME_NEW}&g"
'''

CodePudding user response:

#!/bin/bash

# Replace all instances of "old_string" with "new_string" in the current directory and subdirectories
find . -type f -exec sed -i "s/old_string/new_string/g" {}  

This script uses the find command to search for all files in the current directory and its subdirectories, and the sed command to perform the string replacement on each file.

Note that this script will only work for plain text files, and may not work for binary files. You may need to adjust the script to exclude certain file types or directories from the search.

Additionally, you may want to add more functionality to the script, such as prompting the user for the old and new strings, or providing options to customize the search and replace behavior. You can refer to the find and sed documentation for more information on how to do this.

  • Related