简体   繁体   中英

bash replace one character from the end of string

I need to replace last dot to character '-' in the string.

# a='2.5.2.pl'

Using the following expression:

# echo ${a/%./-}

I expect to get:

2.5.2-pl

but i get

2.5.2.pl

I noticed that it doesn't work only if I need to replace the dot from the end to the beginning. Why does it happen? Of course I can use external programs like awk, sed to solve this problem but I need to solve the problem using only bash.

Thanks for advice!

With bash's Parameter Expansion :

a='2.5.2.pl'
echo "${a%.*}-${a##*.}"

Output:

2.5.2-pl

My way is a bit hacky and uses rev but I tested it and it works!

echo "$(_b=$(echo "$a" | rev); _b=${_b/./-}; echo "$_b" | rev)"

Basically, I just reversed the character order so the last . was first and then used ${var/./-} to replace the dot with a dash and finally reversed the order of the characters again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM