13

I have a file test.txt contains many lines like the following:

hello:123: world
hello:783: world
hello:479: world
......

How to use sed command to replace the lines as follows?

hello:(123, 0): world
hello:(783, 0): world
hello:(479, 0): world
......

Thanks in advance!

19

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

6
  • 3
    this will fail if first column has he123llo, use sed -e 's/\(.*:\)\([0-9]\+\)\(:.*\)/\1(\2, 0)\3/g' instead
    – Rahul
    Sep 8 '16 at 12:08
  • echo "he123llo" | sed -e 's/\([0-9]\+\)/(\1, 0)/g' works just as intended for me with the result "he(123, 0)llo"
    – derdeagle
    Sep 8 '16 at 12:14
  • 1
    Assuming OP wants to process text after :
    – Rahul
    Sep 8 '16 at 12:15
  • 1
    You're right, now I see what you mean.
    – derdeagle
    Sep 8 '16 at 12:18
  • 1
    dude, this -e gave me headache in Mac, it was sed -E
    – juanmf
    May 25 '20 at 18:11
3

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
2

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
2
  • 1
    Damn, I was just about to post awk one. Cool +1
    – Rahul
    Sep 8 '16 at 12:22
  • 1
    ha, I actually tried it out seeing your comments as a learning exercise :)
    – Sundeep
    Sep 8 '16 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.