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


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.


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

Then quote it with helping sed:

sed -r "s/(\w+)/'\1'/g" <(paste -d, -s infile)
  • Thank you. That awk command will work on most of the files I have. If in the future I have a list file that has over 100,00 words, will it still output onto one line? – sh_newbie Oct 22 '17 at 11:48
  • Yes, this will do. – αғsнιη Oct 22 '17 at 11:52
  • Can avoid the ugly and errorprone mixed quotes with awk -vq=\' '{printf q"%s"q", ", $0}' etc somewhat like Sergiy's perl answer – dave_thompson_085 Oct 23 '17 at 9:55

Short printf approach:

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

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

Perl approach:

$ perl -lne '$sq="\x27";push @a,$sq.$_.$sq;END{ print join( ",",@a) }' input.txt                                                                                                                                                           
  • 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                                                                                                                                 
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.