简体   繁体   English

bash从字符串末尾替换一个字符

[英]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. 当然,我可以使用诸如awk,sed之类的外部程序来解决此问题,但我仅需使用bash即可解决问题。

Thanks for advice! 谢谢你的建议!

With bash's Parameter Expansion : 随着bash的参数扩展

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! 我的方法有点hacky,使用了rev但我对其进行了测试,并且可以正常工作!

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. 首先使用${var/./-} ,然后使用破折号代替点,最后再次颠倒字符的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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