sed replace exact match

后端 未结 3 634
暗喜
暗喜 2021-02-03 10:34

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\"

...
         


        
3条回答
  •  悲&欢浪女
    2021-02-03 11:10

    In GNU sed, the following command works:

    sed 's/\/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_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/\/$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.

提交回复
热议问题