Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace single quotes with another character in sed?

I have a flat file where I have multiple occurrences of strings that contains single quote, e.g. hari's and leader's.

I want to replace all occurrences of the single quote with space, i.e.

  • all occurences of hari's to hari s
  • all occurences of leader's to leader s

I tried

sed -e 's/"'"/ /g' myfile.txt 

and

sed -e 's/"'"/" "/g' myfile.txt 

but they are not giving me the expected result.

like image 704
Srihari Avatar asked Jun 28 '13 05:06

Srihari


People also ask

How do you use sed to replace single quotes?

Just use " for the outer quotes in your sed and you can then use ' in the replacement. You don't want "+ unless you might have more than one consecutive " and you want to replace all of them. If you do, use sed -r "s/\\\"+/\\'/g" .

How do you replace a single quote?

Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.

How do you replace special characters in sed?

You need to escape the special characters with a backslash \ in front of the special character. For your case, escape every special character with backslash \ .

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. Output : linux is great os.


2 Answers

Try to keep sed commands simple as much as possible. Otherwise you'll get confused of what you'd written reading it later.

#!/bin/bash sed "s/'/ /g" myfile.txt 
like image 53
Antarus Avatar answered Sep 30 '22 11:09

Antarus


This will do what you want to

echo "hari's"| sed 's/\x27/ /g' 

It will replace single quotes present anywhere in your file/text. Even if they are used for quoting they will be replaced with spaces. In that case(remove the quotes within a word not at word boundary) you can use the following:

echo "hari's"| sed -re 's/(\<.+)\x27(.+\>)/\1 \2/g' 

HTH

like image 28
n3rV3 Avatar answered Sep 30 '22 11:09

n3rV3