justin cress
justin cress

Reputation: 1831

Sed use line number in replacement

Does sed know what line it's on, can it put it in a replacement? I.e. find all occurrences of foo and replace with (x) bar where x is the line number

Upvotes: 1

Views: 520

Answers (1)

Andriy Makukha
Andriy Makukha

Reputation: 8304

Sed has a command =, which only prints the line number to stdout.

You could use it like this:

sed '=' YOURFILE | sed 'N; s/^\([0-9]\+\)\(.*\)\(NEEDLE\)/\1\2(\1) REPLACEMENT/; s/^[0-9]\+\n//'

Example input file roses:

Roses are red,
Violets are blue,
sugar is sweet,
And so are you.

Example command:

sed '=' roses | sed 'N; s/^\([0-9]\+\)\(.*\)\(blue\)/\1\2(\1) violet/; s/^[0-9]\+\n//'

Example output:

Roses are red,
Violets are (2) violet,
sugar is sweet,
And so are you.

Of course, this is simpler with AWK:

awk '{ gsub(/NEEDLE/,"("NR") REPLACEMENT") } 1' YOURFILE

Equivalent example:

awk '{ gsub(/blue/,"("NR") violet") } 1' roses

Upvotes: 3

Related Questions