user1987607
user1987607

Reputation: 2157

sed replace exact match

I want to change some names in a file using sed. This is how the file looks like:

#! /bin/bash

SAMPLE="sample_name"
FULLSAMPLE="full_sample_name"

...

Now I only want to change sample_name & not full_sample_name using sed

I tried this

sed s/\<sample_name\>/sample_01/g ...

I thought \<> could be used to find an exact match, but when I use this, nothing is changed.

Adding '' helped to only change the sample_name. However there is another problem now: my situation was a bit more complicated than explained above since my sed command is embedded in a loop:

while read SAMPLE
do
    name=$SAMPLE
    sed -e 's/\<sample_name\>/$SAMPLE/g' /path/coverage.sh > path/new_coverage.sh
done < $1

So sample_name should be changed with the value attached to $SAMPLE. However when running the command sample_name is changed to $SAMPLE and not to the value attached to $SAMPLE.

Upvotes: 21

Views: 76538

Answers (3)

Himanshu Chauhan
Himanshu Chauhan

Reputation: 832

@user1987607

You can do this the following way:

sed s/"sample_name">/sample_01/g

where having "sample_name" in quotes " " matches the exact string value.

/g is for global replacement.

If "sample_name" occurs like this ifsample_name and you want to replace that as well then you should use the following:

sed s/"sample_name ">/"sample_01 "/g

So that it replaces only the desired word. For example the above syntax will replace word "the" from a text file and not from words like thereby.

If you are interested in replacing only first occurence, then this would work fine

sed s/"sample_name"/sample_01/

Hope it helps

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74695

In GNU sed, the following command works:

sed 's/\<sample_name\>/sample_01/' file

The only difference here is that I've enclosed the command in single quotes. Even when it is not necessary to quote a sed command, I see very little disadvantage to doing so (and it helps avoid these kinds of problems).

Another way of achieving what you want more portably is by adding the quotes to the pattern and replacement:

sed 's/"sample_name"/"sample_01"/' script.sh

Alternatively, the syntax you have proposed also works in GNU awk:

awk '{sub(/\<sample_name\>/, "sample_01")}1' file

If you want to use a variable in the replacement string, you will have to use double quotes instead of single, for example:

sed "s/\<sample_name\>/$var/" file

Variables are not expanded within single quotes, which is why you are getting the the name of your variable rather than its contents.

Upvotes: 10

anubhava
anubhava

Reputation: 786091

I believe \< and \> work with gnu sed, you just need to quote the sed command:

sed -i.bak 's/\<sample_name\>/sample_01/g' file

Upvotes: 36

Related Questions