1753724 Members
4840 Online
108799 Solutions
New Discussion юеВ

Re: Adding Single Quotes

 
SOLVED
Go to solution
Allanm
Super Advisor

Adding Single Quotes

I want to add single quotes to each entry in a file like this -

'xxxxxx'

currently its just xxxxxx and there are 2000 enteries in all for which I need to add the quotes to.

Currently the file is like this -

xxxxxx
xxxxxx
xxxxxx
.
.
.
xxxxxx

and want to change this to -

'xxxxxx'
.
.
.
.
'xxxxxx'
6 REPLIES 6
Allanm
Super Advisor

Re: Adding Single Quotes

James R. Ferguson
Acclaimed Contributor
Solution

Re: Adding Single Quotes

Hi:

# cat ./myfile
this is something
another
thing 1
thing 2
here is more

# perl -pe 's/(\S+)/\047$1\047/g' myfile
'this' 'is' 'something'
'another'
'thing' '1'
'thing' '2'
'here' 'is' 'more'

...and if you want an inplace update:

# perl -pi.old -e 's/(\S+)/\047$1\047/g' myfile

...which automatically backs up the unchanged file as 'myfile.old' too.

Regards!

...JRF...
Allanm
Super Advisor

Re: Adding Single Quotes

JRF can you explain the regex for my own understanding.

Thanks,
Allan.
James R. Ferguson
Acclaimed Contributor

Re: Adding Single Quotes

Hi (again) Allanm:

The regex substitutes a non-whitespace character sequence with a single quote, the character sequence and another single quote. A non-whitespace character is denoted by '\S'. The '+' says one or more of them. The parenthesis capture what is seen and the '\1' is a backreference to what was last captured. The '\047' is the Ascii code for a single quote which makes commandline substitution easier to do. The 'g' says to "g"lobally repeat the substitution as many times as necessary on each line.

Please don't forget to re-open this thread to evaluate these answers :-)

Regards!

...JRF...
Allanm
Super Advisor

Re: Adding Single Quotes

thanks!
Dennis Handly
Acclaimed Contributor

Re: Adding Single Quotes

I would typically use vi if one file:
:%s/^/'/
:%s/$/'/
Translating to sed:
sed -e "s/^/'/" -e "s/$/'/" file
Or harder:
sed -e "s/^\(.*\)\$/\'\1'/" file