jojo
jojo

Reputation: 13863

How can I replace dot in Bash shell?

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?

Upvotes: 2

Views: 13518

Answers (4)

Stanislav
Stanislav

Reputation: 2677

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

Upvotes: 3

johnsyweb
johnsyweb

Reputation: 141918

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

Upvotes: 3

Dennis Williamson
Dennis Williamson

Reputation: 360495

If you just want to replace the dot:

var="abc edg.txt"
echo ${var/./---}

Upvotes: 13

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263077

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

Upvotes: 10

Related Questions