如何在 Bash shell 中替换点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4482225/
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 can I replace dot in Bash shell?
提问by jojo
I want to do something like this:
我想做这样的事情:
echo "abc edg.txt" | awk -F. '{print var="abc edg.txt"
echo ${var/./---}
"---"}'
I expect the result should be:
我希望结果应该是:
abc edg---txt
abc edg---txt
but it turns out to be:
但结果是:
abc edg.txt---abc edg
abc edg.txt---abc edg
What is causing this behavior, and how can I fix my code to produce the output that I expect?
是什么导致了这种行为,我该如何修复我的代码以产生我期望的输出?
回答by Paused until further notice.
If you just want to replace the dot:
如果您只想替换点:
$ echo "abc edg.txt" | awk -F. '{print "---"}'
abc edg---txt
回答by Frédéric Hamidi
In awk, $0evaluates to the whole record, and field indexes are one-based.
在 awk 中,$0对整个记录求值,字段索引是从一开始的。
You probably want to do:
你可能想做:
$ foo="abc edg.txt" ; IFS=. ; a=($foo) ; echo ${a[0]}---${a[1]}
abc edg---txt
回答by Johnsyweb
Frédéric Hamidi's answerfixes your problem with awk, but since you asked about how to split a string by dot in Bash shell, here is an answer that does exactly that, without resorting to awk:
Frédéric Hamidi 的回答解决了您的问题awk,但是由于您询问了如何在 Bash shell 中按点分割字符串,这里有一个答案就是这样做的,而无需求助于awk:
$ foo="abc edg.txt" ; echo ${foo%.*}---${foo##*.}
abc edg---txt
It's even easier if you only want to split on the last'.' in the string:
如果您只想在最后一个'.'上拆分,那就更容易了。在字符串中:
echo "abc edg.txt" | sed 's/\./~~/g'
回答by Stanislav
Awkis great, but there are other ways to subsitute.
Awk很棒,但还有其他替代方法。
With sedyou can get all of the dots and not only the first one.
有了sed你可以得到所有的点,而不是只有第一个。
variable="abc here.is.more.dot-separated text"
echo ${variable}| sed 's/\./~~/g'
Out: abc edg~~txt
出去: abc edg~~txt
The expression sed 's/\./~~/g'is equivalent to "substitute \.(dot) with ~~, globally".
该表达式sed 's/\./~~/g'等效于“\.用~~, 全局替换(点)”。
Out: abc here~~is~~more~~dot-separated text
出去: abc here~~is~~more~~dot-separated text

