Andrey Rubliov
Andrey Rubliov

Reputation: 407

How to append suffix to all string matched regular expression in unix

I need to replace all occurrences of string in specific format (in my case colon followed by some number) with same string with suffix in a file, like this:

:123456 -> :123456_suffix

Is there a way to do it with sed or other unix command-line tool?

Upvotes: 0

Views: 1645

Answers (2)

choroba
choroba

Reputation: 242038

Sed should do that:

sed -i~ -e 's/:\([0-9]\{1,\}\)/:\1_suffix/g' file
                ^  ^  ^      ^   ^        ^
                |  |  |      |   |        |
    start capture  |  |    end   |  globally, i.e. not just the first
    group          |  | capture  |              occurrence on a line
           any digit  |          the first capture
                 one or          group contents
                 more times

If -i is not supported, just create a new file and replace the old one:

sed ... > newfile
mv oldfile oldfile~ # a backup
mv newfile oldfile

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174806

use sed,

sed 's/\(:[0-9]\+\)/\1_suffix/g' file

add -i modifier , if you want to do an in-place edit.

Upvotes: 2

Related Questions