I want to do something like this:
echo "abc edg.txt" | awk -F. '{print $0"---"$1}'
I expect the result should be:
abc edg---txt
but it turns out to be:
abc edg.txt---abc edg
What is causing this behavior, and how can I fix my code t开发者_如何转开发o produce the output that I expect?
If you just want to replace the dot:
var="abc edg.txt"
echo ${var/./---}
In awk, $0
evaluates to the whole record, and field indexes are one-based.
You probably want to do:
$ echo "abc edg.txt" | awk -F. '{print $1"---"$2}'
abc edg---txt
Frédéric Hamidi's answer fixes 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
:
$ foo="abc edg.txt" ; IFS=. ; a=($foo) ; echo ${a[0]}---${a[1]}
abc edg---txt
It's even easier if you only want to split on the last '.' in the string:
$ foo="abc edg.txt" ; echo ${foo%.*}---${foo##*.}
abc edg---txt
Awk
is great, but there are other ways to subsitute.
With sed
you can get all of the dots and not only the first one.
echo "abc edg.txt" | sed 's/\./~~/g'
Out: abc edg~~txt
The expression sed 's/\./~~/g'
is equivalent to "substitute \.
(dot) with ~~
, globally".
variable="abc here.is.more.dot-separated text"
echo ${variable}| sed 's/\./~~/g'
Out: abc here~~is~~more~~dot-separated text
精彩评论