user3252809
user3252809

Reputation: 136

remove blank space after single quotes in a string (using awk or sed)

Below is the input file:

select a, b,c, a1 as ' value1 ', a2 as ' value2 ', d from table1;

Given file can have any number of aliases. I want to remove space between the quotes. The desired output is:

select a,b,c, a1 as 'value1', a2 as 'value2',d from table1;

Will it be possible using awk or sed?

Upvotes: 0

Views: 249

Answers (3)

drewyupdrew
drewyupdrew

Reputation: 1609

I had a hard time using sed because basic and extended Posix/GNU both don't recognize the non-greedy quantifier ?. Anyway, if you can use perl, here's one way to do it:

perl -pe "s/'\s*(.*?)\s*'/'\1'/g" input_file.txt

 

Edit:

Ah yes, I like the solution @edmorton gave. You can use [^'*] instead of the greedy quantifier ?. So to use sed you can do:

sed -r "s/'\s+([^']*)\s+'/'\1'/g" input_file.txt

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203635

$ sed -r "s/' +([^']*) +'/'\1'/g" file
select a, b,c, a1 as 'value1', a2 as 'value2', d from table1;

Upvotes: 2

jas
jas

Reputation: 10865

With gawk you can use gensub:

$ cat q.txt
select a, b,c, a1 as ' value1 ', a2 as ' value2 ', d from table1;

$ cat q.awk
{ print gensub(/' *([^' ]+) *'/, "'\\1'", "g") }

$ gawk -f q.awk q.txt
select a, b,c, a1 as 'value1', a2 as 'value2', d from table1;

Upvotes: 2

Related Questions