4

I want to take a file that has a list of words on each line of its own eg.

act
bat
cat
dog
eel

and put them into one line with comma separated and quoting them. So that it turns out like:

'act', 'bat', 'cat', 'dog', 'eel',

so, a single quote, then the word, then another single quote, then a comma, then a space. Then output to a new file with a new name.

αғsнιη
  • 41,407

4 Answers4

3

Short printf approach:

printf "'%s', " $(< file) > output
2

Using sed and tr:

$ sed -e "s/^/'/" -e "s/$/', /" file | tr -d '\n'
'act', 'bat', 'cat', 'dog', 'eel',

(with no newline at the end of the output)

The sed inserts the quotes at the start and end of every line of input (and a comma and space after), while tr removes the newlines.

Redirect the output to a file:

$ sed -e "s/^/'/" -e "s/$/', /" file | tr -d '\n' >newfile
Kusalananda
  • 333,661
1

Using awk:

awk '{printf ("'\'%s\'', ", $0)}' infile > new_file
'act', 'bat', 'cat', 'dog', 'eel',

Or to avoid adding an extra comma at the end, use below instead.

awk '{printf S"'\''"$0"'\''";S=", "}'
'act', 'bat', 'cat', 'dog', 'eel'

Or using paste without quoting.

paste -d, -s infile
act,bat,cat,dog,eel

Then quote it with helping sed:

sed -r "s/(\w+)/'\1'/g" <(paste -d, -s infile)
'act','bat','cat','dog','eel'
αғsнιη
  • 41,407
0

Perl approach:

$ perl -lne '$sq="\x27";push @a,$sq.$_.$sq;END{ print join( ",",@a) }' input.txt                                                                                                                                                           
'act','bat','cat','dog','eel'
  • here we use hex value for single quote stored in sq variable, and for each line read from file, we wrap it into single quotes
  • each line with single quotes is pushed into a array
  • once everything is read, join creates a single string of text out of each array item, joined via ,

Python approach along the same lines:

$ python -c 'import sys;sq="\x27";print ",".join([ sq + l.strip() + sq  for l in sys.stdin  ])' < input.txt                                                                                                                                 
'act','bat','cat','dog','eel'
  • here we redirect input file into the command's stdin stream via shell < operator
  • each line is stripped from newline character \n via strip method, quoted via same idea described in Perl approach
  • all lines are processed into a list via [item for item in iterable] structure (known as list comprehension)
  • and finally ",".join() lets us create a nice string out of all list items