user2814482
user2814482

Reputation: 651

search and replace with sed not working

I would like to use sed for search and replace, but it doesn't seem to be working. I guess I'm making a stupid mistake I can't spot.

here is my file.txt:

PFPR03  PA1448770
PFPR03  PA1448780
PFPR03  PA1448790
PFPR03  PA1448800
PFPR03  PA1448810
PFPR03  PA1448830
PFPR03  PA1448840
PFPR03  PA1448850
PFPR03  PA1448860
PFPR03  PA1448870

I want to change PA1448770 to PA14_48770, ie. adding an underscore after the PA14.

Here are a few examples of what I've tried, none of them are affecting the file at all:

sed 's/^PA14/PA14_/g' file.txt
sed 's/^PA14([0-9]*)/PA14_\1/' file.txt 

Any help is appreciated,

Upvotes: 4

Views: 4995

Answers (2)

John Pink
John Pink

Reputation: 637

You are using this token ^, which means start of string. That's either the beginning of a line, or of an entire file, but certainly not the beginning of a word. So this should work :

sed 's/PA14/PA14_/g' file.txt

edit

I highly recommend regex101 to practice your regex. You can test your expressions in live, and they have lot's of good explanations about tokens.

Upvotes: 2

anubhava
anubhava

Reputation: 784938

It is because ^ means line start. Use \b for word boundary:

sed 's/\bPA14/PA14_/g' file
PFPR03  PA14_48770
PFPR03  PA14_48780
PFPR03  PA14_48790
PFPR03  PA14_48800
PFPR03  PA14_48810
PFPR03  PA14_48830
PFPR03  PA14_48840
PFPR03  PA14_48850
PFPR03  PA14_48860
PFPR03  PA14_48870

PS: On OSX (BSD) sed use:

sed 's/[[:<:]]PA14/PA14_/g' file

Upvotes: 1

Related Questions