Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surround every line with single quote except empty lines

My goal is to add a single apostrophe to every line in the file and skip empty lines.

file.txt:

Quote1
Quote2

Quote3

So far I have used sed:

sed -e "s/\(.*\)/'\1'/"

Which does the job but creates apostrophes also in empty lines:

'Quote1'
'Quote2'
''
'Quote3'

My goal:

'Quote1'
'Quote2'

'Quote3'

How could I achieve this by using sed, or maybe it should it be awk.

like image 460
AndroidFreak Avatar asked Jan 02 '23 01:01

AndroidFreak


2 Answers

.* means zero or more characters, you want 1 or more characters which in any sed would be ..*:

$ sed "s/..*/'&'/" file
'Quote1'
'Quote2'

'Quote3'

You can also write that regexp as .\+ in GNU sed, .\{1,\} in POSIX seds, and .+ in GNU or OSX/BSD sed when invoked with -E.

The above assumes lines of all blanks should be quoted. If that's wrong then:

$ sed "s/.*[^[:blank:]].*/'&'/" file
'Quote1'
'Quote2'

'Quote3'

In any awk assuming lines of all blanks should be quoted:

$ awk '/./{$0="\047" $0 "\047"}1' file
'Quote1'
'Quote2'

'Quote3'

otherwise:

$ awk 'NF{$0="\047" $0 "\047"}1' file
'Quote1'
'Quote2'

'Quote3'

You can see the difference between the above with this:

$ printf '   \n' | sed "s/..*/'&'/"
'   '
$ printf '   \n' | sed "s/.*[^[:blank:]].*/'&'/"

$ printf '   \n' | awk '/./{$0="\047" $0 "\047"}1'
'   '
$ printf '   \n' | awk 'NF{$0="\047" $0 "\047"}1'

$
like image 179
Ed Morton Avatar answered Jan 05 '23 17:01

Ed Morton


One way:

awk '$1{$0 = q $0 q}1' q="'" file

Add quotes only if 1st column($1) has some value. 1 to print every line.

like image 43
Guru Avatar answered Jan 05 '23 17:01

Guru