7

I have a text file which contains this line:

set stime = '0 0'

I need to change that to:

set stime = '0 4'

I tried these commands:

sed -i 's/original/new/g' file.txt

and

awk '{gsub(/pattern/,"replacement")}' file 

but they don't work. I guess it is because of the apostrophe in the pattern. How can I do this correctly?

8

In order to escape single quote ', you should use double quotes: ".

In order to update in-place you should use sed -i

The following code should update in-place, and escape the single quote:

sed -i "s/set stime = '0 0'/set stime = '0 4'/g" input_file_name
  • " used to escape single quote, then can't it be sed -i "s/4/1/g filename" ? – d a i s y Mar 1 '17 at 11:51
  • @Lnux That would replace every instance of 4 in the entire file with 1, which is not what was asked for. Also, the filename shouldn't be in the quotes; there's two arguments: the pattern (in quotes so it can contain spaces and punctuation); and the filename (which might also be in quotes for the same reason). – IMSoP Mar 1 '17 at 14:16
  • Technically, nothing is being "escaped" here; you are just able to use single quotes because they don't accidentally end the string early. Escaping would be adding a \ in front of a quote, which is the only way if you need to include both types of quotes, e.g. sed "s/some \"double quotes\"/some 'single quotes'/g" filename – IMSoP Mar 1 '17 at 14:19
  • filename outside of "..just a typing mistake and thanks for technical clarification – d a i s y Mar 1 '17 at 15:15
5

You have a few choices:

  1. Use double quotes instead of single quotes for the sed or awk commands:

    sed -i "s/set stime = '0 0'/set stime = '0 4'/g" file
    

    or

    awk "{gsub(/set stime = '0 0'/,\"set stime = '0 4'\")}1;" file 
    
  2. Save the pattern in a shell variable and use double quotes:

    replacement="set stime = '0 4'"
    pattern="set stime = '0 0'"
    

    then

    sed "s/$pattern/$replacement/g" file
    

    or

    awk -vpat="$pattern" -vrep="$replacement" '{gsub(pat,rep)}1;' file 
    
  3. Don't use the entire pattern. Just find the right line and replace only what needs to be changed, avoiding the quote. For example, if you only have one occurrence of set stime, you can do:

    sed '/set stime/{s/0 0/0 4/}' file 
    

    or

    awk '$1=="set" && $2=="time"{sub("0 0","0 4")}1' file
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.