Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- help_message="
- Script have 2 modes: interactive and noninteractive.
- For interactive mode use args:
- -i insensitive search for replacement
- -v verbose entered args
- -I start interactive mode
- Exemple:
- scriptname -I [-i]
- For noninteractive use args:
- -i insensitive search for replacement
- -v verbose entered args
- -d path to target directory
- -t a word or expression that must be replaced
- -r word or expression to be replaced by
- Exemple:
- scriptname [-i] -d /path/to/dir -t 'exemple_1' -r 'i love exemples'
- or with regexp:
- scriptname [-i] -d /path/to/dir -t 'ex..ple_1$' -r 'i love exemples'
- "
- function main_work(){
- for arg in $script_args; do case $arg in "-i") insensitive_trigger="1";; "-v") dbg="1";; esac; done
- [ "$interactive_trigger" == "1" ] && {
- [[ "$dir_path" || "$old_expression" || "$new_expression" ]] && echo -e "why you use args in interactive mode?\n"
- read -r -p "path to work dir > " dir_path
- IFS= read -r -p "target word > " old_expression
- IFS= read -r -p "replacement word > " new_expression
- }
- [ ! -d "$dir_path" ] && { echo -e "\nDirectory \"$dir_path\" does not exist\nMake sure that the path exists"; error_exit_trigger="1"; }
- [ -z "$old_expression" ] && { echo -e "\nNot found the target word"; error_exit_trigger="1"; }
- [ -z "$new_expression" ] && { echo -e "\nNot found the word for replacement"; error_exit_trigger="1"; }
- [ "$error_exit_trigger" == "1" ] && exit
- for file in $(find $dir_path -type f); do
- if [ "$insensitive_trigger" == "1" ]; then
- sed -E -i -e "s/$old_expression/$new_expression/ig" $file
- else
- sed -E -i -e "s/$old_expression/$new_expression/g" $file
- fi
- done
- [ "$dbg" == "1" ] && echo -e "\ndir path : $dir_path\ntarget word: $old_expression\nreplaced by: $new_expression\ninsensitive: $insensitive_trigger\n"
- echo -e "Done\nHave a nice day"
- exit
- }
- function error_handler(){
- error_value="$OPTARG"
- [ "$error_value" == "d" ] && {
- echo -e "Err: -d must contain folder path argument"
- error_exit_trigger="1"
- }
- [ "$error_value" == "t" ] && {
- echo -e "Err: -t must contain target word or expression"
- error_exit_trigger="1"
- }
- [ "$error_value" == "r" ] && {
- echo -e "Err: -r must contain target word or expression for replacement"
- error_exit_trigger="1"
- }
- [ "$error_exit_trigger" == "1" ] && {
- echo "For help use -h"
- exit
- }
- }
- script_args="$@"
- insensitive_trigger="0"
- error_exit_trigger="0"
- dbg="0"
- for arg in $script_args;do
- case $arg in
- "-h"|"--help") echo "$help_message" && exit ;;
- "-I") interactive_trigger="1"; main_work; ;;
- esac
- done
- while getopts ":d:t:r:" arg;do
- case $arg in
- "d") dir_path="$OPTARG" ;;
- "t") old_expression="$OPTARG" ;;
- "r") new_expression="$OPTARG" ;;
- :) error_handler ;;
- esac
- done
- main_work
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement