How to use sed to replace numbers with parenthese?
How do you like this one? I hope it is what you needed.
sed -e 's/\([0-9]\+\)/(\1, 0)/g'
Test
echo "hello:123: world
hello:783: world
hello:479: world" | sed -e 's/\([0-9]\+\)/(\1, 0)/g'
Result
hello:(123, 0): world
hello:(783, 0): world
hello:(479, 0): world
POSIXly:
sed 's/[0-9]\{1,\}/(&, 0)/' < file
Would replace the first occurrence of a series of one or more (\{1,\}
) decimal digits with (&, 0)
(where &
is the text being replaced) on each line.
Some sed
implementations have a -E
option for using extended regular expressions (ERE) instead of basic ones (BRE), when you can use +
in place of \{1,\}
. -E
might make it to the next version of the POSIX specification:
sed -E 's/[0-9]+/(&, 0)/' < file
Some sed
implementations like GNU sed
support \+
as a BRE alias for \{1,\}
though that's not portable/standard.
To use perl regular expressions which are becoming a new de-facto standard for regular expressions, you can use... perl
:
perl -pe 's/\d+/($&, 0)/' < file
Assuming input has :
separated text and 2nd column needs to be changed:
$ awk 'BEGIN{ FS=OFS=":" } {$2 = "("$2", 0)"} 1' ip.txt
hello:(123, 0): world
hello:(783, 0): world
hello:(479, 0): world
Or, with perl
$ perl -F: -lane '$F[1] = "($F[1], 0)"; print join ":",@F' ip.txt
hello:(123, 0): world
hello:(783, 0): world
hello:(479, 0): world