Replace a pattern containing an apostrophe within a file
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?
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
You have a few choices:
-
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
-
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
-
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