bash 如何用另一个字符替换bash中字符串的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48743723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace the last char of a string in bash with another char
提问by DenCowboy
I have strings which represent versions (always in the following format):
我有代表版本的字符串(始终采用以下格式):
1.0.0
1.1.0
1.5.0
20.189.0
456874.0.0
The last part of the string will always be .0
.
Now I'm searching for a way in bash how I can replace this with .X
字符串的最后一部分将始终是.0
. 现在我正在 bash 中寻找一种方法来替换它.X
1.0.X
1.1.X
9.5.X
20.189.X
...
回答by Viktor Khilin
sed -i 's/.$/X/' filename
sed -i 's/.$/X/' filename
It will replace last char by X
in each line, rewrite file filename
.
它将X
在每一行中替换最后一个字符,重写文件filename
。
回答by anubhava
Using bash
manipulation:
使用bash
操纵:
str='1.0.0'
echo "${str/%.0/.X}"
1.0.X
or else:
要不然:
echo "${str%.0}.X"
1.0.X
回答by Dervi? Kay?mba??o?lu
very simple approach would be
非常简单的方法是
str=testString
echo ${str%?}X
it just select string without last character and appends X as a trailing character
它只是选择没有最后一个字符的字符串并附加 X 作为尾随字符
回答by James Brown
If the strings are in file file
:
如果字符串在文件中file
:
$ cat file
1.0.0
456874.0.0
1.1.666
(notice the last one above)
(注意上面最后一个)
$ for s in $(cat file) ; do echo ${s%.*}.X ; done
1.0.X
456874.0.X
1.1.X
回答by David C. Rankin
Since we have bash, we can also use the super-simple "index to the last char and replace it, e.g.
由于我们有 bash,我们还可以使用超级简单的“索引到最后一个字符并替换它,例如
str=1.0.0
To index to the last char you use ${str:0:$((${#str}-1))}
(which is just str:0:to_last-1
) so to replace the last character, you just add the new last character at the end, e.g.
要索引到您使用的最后一个字符${str:0:$((${#str}-1))}
(只是str:0:to_last-1
)以便替换最后一个字符,您只需在末尾添加新的最后一个字符,例如
$ str=1.0.0
$ echo ${str:0:$((${#str}-1))}X
1.0.X
There are always multiple ways to skin-the-cat in bash.
总是有多种方法可以在 bash 中剥猫皮。
(personally, I'd use the parameter expansion with substring removal-- but those were already taken...)
(就我个人而言,我会使用带有子字符串删除的参数扩展——但那些已经被采用了......)