How can I replace dot in Bash shell?
Solution 1
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
Solution 2
If you just want to replace the dot:
var="abc edg.txt"
echo ${var/./---}
Solution 3
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
Solution 4
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
Prophet
Updated on June 04, 2022Comments
-
Prophet almost 2 years
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 to produce the output that I expect?
-
johnsyweb over 13 yearsYes, this is simplest way to replace. The question definitely asked how to 'split' when I answered!
-
glenn jackman over 13 yearsYou want
${foo%.*)
to strip off only the last dot and test