Combine List of Words into One Line and Add Characters Using awk or sed

awkpastesedtext processing

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.

Best Answer

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'
Related Question