Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace backtick with single quote using sed or awk

Tags:

regex

bash

php

sed

awk

I want to replace all backticks (´) with single quotation marks (') in specific text document using sed or awk inside of PHP shell_exec() without using hexadecimal or octal code.

At first, I tried these commands running inside of shell script:

sed -e 's/´/'"'"'/g' file.txt;
sed -e 's/\´/'"'"'/g' file.txt;
sed -e 's/´/'/g' file.txt;
sed -e 's/\´/'/g' file.txt;
sed -e 's/"´"/'"'"'/g' file.txt;
awk '{gsub(/\´/, "\'" ) }1' file.txt;

but none of these worked.

Example of input.txt file:

abc´def´123`foo'456;

Example of output.txt file:

abc'def'123`foo'456

Using sed command running from terminal this solution works:

echo "a´b´c;" | sed "s/´/'/g"

and output is:

a'b'c;

but running it from executable file test.sh:

#!bin/bash
sed "s/´/'/g" input.txt > output.txt

as shell script executed by command

bash test.sh

it doesn't work and content of output.txt file is same as content of input.txt file.

However, with forward tick it works and result of

#!bin/bash
sed "s/\`/'/g" input.txt > output.txt

is output.txt file with content

abc´def´123'foo'456;

However, when I try to replace backward ticks with single quotation marks using hex or octal representation of characters it works like a charm.

Using sed:

input.txt  - abc´def´123`foo'456;
command    - sed 's/\xB4/'"'"'/g' input.txt > output.txt;
output.txt - abc'def'123`foo'456

Using awk:

input.txt  - abc´def´123`foo'456;
command    - awk '{gsub(/\264/, "\047" )}1' input.txt > output.txt;
output.txt - abc'def'123`foo'456

Problem is, that I'm using another script applied to the document with mentioned script that replaces every hexadecimal or octal code with its literal representation. I'm able to do it another way, I'm just curious if mentioned replacement can be used without using hex or octal code.

like image 478
Matúš Frisík Avatar asked Oct 17 '25 05:10

Matúš Frisík


2 Answers

You can use tr with appropriate quoting:

s='abc´def´123´foo'

tr '´' "'" <<< "$s"
abc'def'123'foo

Running tr on a file:

tr '´' "'" < file
like image 114
anubhava Avatar answered Oct 19 '25 20:10

anubhava


I don't know about calling scripts from php but did you try just:

sed "s/´/'/g" file.txt

Look:

$ echo "a´b" | sed "s/´/'/g"
a'b

I think you're using the wrong tick since the tr solution you say works is replacing a different tick from the one you asked to replace in your question (forward tick vs backward tick). If so then you WOULD need to escape the backtick:

sed "s/\`/'/g" file.txt 

$ echo "a\`b" | sed "s/\`/'/g"
a'b
like image 42
Ed Morton Avatar answered Oct 19 '25 20:10

Ed Morton