Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed replace exact match

Tags:

regex

sed

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.

like image 434
user1987607 Avatar asked Nov 10 '14 18:11

user1987607


People also ask

How to replace everything after the match in sed command?

The following ` sed ` command shows the use of ‘ c ‘ to replace everything after the match. Here, ‘ c ‘ indicates the change. The command will search the word ‘ present ‘ in the file and replace everything of the line with the text, ‘ This line is replaced ‘ if the word exists in any line of the file.

How to use variable in replacement string in SED?

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

How to replace all occurrences of the search pattern in SED?

With the global replacement flag sed replaces all occurrences of the search pattern: As you might have noticed, the substring foo inside the foobar string is also replaced in the previous example. If this is not the wanted behavior, use the word-boundary expression ( \b) at both ends of the search string.

How to get the exact value of a string in SED?

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.


1 Answers

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
like image 156
anubhava Avatar answered Sep 20 '22 16:09

anubhava