user2672739
user2672739

Reputation: 143

Replace string on given input

I need to replace particular string based on country input which get passed to my bash script program

I am trying to change the existing code

table_value=$1
ctry_input=$2
final_var=$(echo ${table_value}| sed -e "s/\@ctry/${ctry_input}/")

Input values

if table_value=random_@ctry_final 
and ctry=KL
then final_var=random_KL_final
if table_value=source_@ctry_final
and ctry in (nz,uk,us)
then final_var=source_nz_final subsequently the string would be replaced for uk and us
if table_value=source_@ctry_final
and ctry in (aus,cn)
then final_var=diff_aus_final. In this case source_@ctry_final should be replaced as diff_aus_final. source string needs to be replaced as diff for countries under aus,cn

Is there a way to tweak the existing variable code instead of using if else

Upvotes: 0

Views: 46

Answers (1)

Walter A
Walter A

Reputation: 20012

I have added quotes in echo "${table_value}", that is not needed for the solution but is a good practice.
I use the sed option -r avoiding backslashes for special characters (option -e is not needed).
After the original code I added an additional command replacing a part when the string looks like source_aus_ or source_cn_.

final_var=$(echo "${table_value}"| sed -r "s/\@ctry/${ctry_input}/;s/source_(aus|cn)_/diff_\1_/" )

Upvotes: 1

Related Questions