user2861188
user2861188

Reputation: 13

search and replace nth occurence in a file

Does anyone know any unix commands/perl script that would replace a specific occurence

my file is hello.txt

 number         555
 number         555
 number         555

now i want to replace the second occurence with number 666.

i have been trying this command

perl -n -i -e "s/number\\s+555/number 666/g" hello.txt'

which is changing all the occurences.

one liners will be really helpful.

Upvotes: 0

Views: 1563

Answers (4)

mpapec
mpapec

Reputation: 50637

$. holds line number for current file handle and can be used for given input file like,

perl -i -pe 's/number\s+555/number 666/ if $. == 2' hello.txt

or if number part can be dropped out,

perl -i -pe 's/555/666/ if $. == 2' hello.txt

Upvotes: 1

jkshah
jkshah

Reputation: 11703

Try using sed

sed -r -i.bak ':a;N;$!ba;s/(number\s+)555/\1666/2' file

Output:

 number         555
 number         666
 number         555

Reference SO question

Upvotes: 0

user184968
user184968

Reputation:

Does anyone know any unix commands: I believe awk is suitable for this task (http://www.grymoire.com/Unix/Awk.html).

awk '{if (NR == 2) {gsub("555", "666", $0);} print $0; } ' hello.txt

Upvotes: 0

Kuthbudin
Kuthbudin

Reputation: 11

I read content of file hello.txt to array then joined to get $str. Here it will replace 2nd occurrence with i initialized to 0. Try this search and replace in one liner.

 $str =~ s/(number\s+555)/ ++$i==2 ? "number 666": $1/gse;

Upvotes: 0

Related Questions