I have a data file with rows of comma-separated fields like this:

United Kingdom, GB, +44

and I want to produce the following output for each line in the file:

<option value="GB">United Kingdom +44</option>

I got as far as follows with awk, but after adding the angle brackets I am getting mangled output:

    print "<option value=\"" $2 "\">";                                                                                                                                                                                                                         


2 Answers 2


awk's printf function can be easier to use when it comes to embedded quotes.

awk -F, '{printf("<option value=\"%s\">%s %s</option>\n", $2, $1, $3)}'

The problem with that is that you also have whitespace between each field. We can use the gsub function to trim each field.

awk -F, '{gsub(/^ +| +$/,"", $2); printf("<option value=\"%s\">%s %s</option>\n", $2, $1, $3)}'

Or what's easier is to change our field separator: awk -F' *, *' '{printf("%s %s\n", $2, $1, $3)}'

If you need to trim multiple fields then it might be better to use a loop or a function (depending on the situation). See https://stackoverflow.com/questions/9985528/how-can-i-trim-white-space-from-a-variable-in-awk for more info.

  • I don't get the correct output with this. The "</option>" at the end does not appear at the end of each line. It only appears on the last line e.g. </option>alue="+260">Zambia ZM <option value="+263">Zimbabwe ZW</option>
    – user350403
    May 29, 2019 at 18:25
  • 2
    @M.K. looks like your csv has CRLF line delimiters, convert to unix first with dos2unix. May 29, 2019 at 18:30
  • @StéphaneChazelas thanks, that was the problem!
    – user350403
    May 29, 2019 at 19:44


awk -F "," '{print "<option value="$2">United Kingdom "$3"</option>"}' filename| sed 's/GB/"&"/g'


<option value= "GB">United Kingdom  +44</option>
  • unfortunately, this hardcodes (in the sed statement) the GB value in column 2; shouldn't it surround the option value no matter what it is?
    – Jeff Schaller
    Jun 3, 2019 at 17:32

You must log in to answer this question.