I need to replace all spaces which exist within quotes. I have several columns yet only one column has quoted output containing spaces which is throwing off my columns when using column -t

"UDP netprobe"
"ACL allow"
"ACL deny"

  • the columns are delimited with what character? by default column is using whitespaces as delimiter of the input file, you can change it with -s 'delimiter' (where delimiter is a set of characters). May 23, 2018 at 17:16

5 Answers 5


With perl:

perl -pe 's{".*?"}{$& =~ y/ /_/r}ge' file

With sed

sed -E ':A;s/("[^ "]+) ([^"]*")/\1_\2/;tA' infile
  • This is the answer
    – harish2704
    May 27, 2019 at 13:00
  • You are genius! To those who wonder: :A defines a label which can be used in "goto" statements. tA goes back to the :A label if substitution (s) was successful.
    – Noam Manos
    Sep 9, 2020 at 10:27

In general, a proper CSV parser would be recommended. In this simple case, awk will do: use double quote as the field separator character, and:

awk -F '"' -v OFS='"' '{
    for (i=2; i<=NF; i+=2)
        gsub(/[[:blank:]]/, "_", $i)
}' <<END
first "UDP netprobe" hello
second "ACL allow" friendly "oops, another quoted field"
third "ACL deny" world
first "UDP_netprobe" hello
second "ACL_allow" friendly "oops,_another_quoted_field"
third "ACL_deny" world

For the one-liner fans:

awk -F\" '{for(i=2;i<=NF;i+=2)gsub(/[[:blank:]]/,"_",$i)}1' OFS=\" file
  • | awk -F'"' '{for(i=2;i<=NF;i++)if(i%2==0)gsub(" ","_",$i);}1' OFS="" worked the same way. THANK YOU!!
    – Steve
    May 23, 2018 at 12:37
  • sure, but there's no need for the extra test if you know you only want every 2nd field. May 23, 2018 at 12:38

Using sed:

sed 's/\("[^"]\+\) \([^"]\+"\)/\1_\2/g' file

The regex looks for word within double, and the command replaces space with underscore.

  • Did not work for me.
    – unxnut
    May 23, 2018 at 13:01
sed 's/\(\"[^" ]*\) \([^"]*\"\)/\1_\2/g' file

Caveat: it only works with a single space between a pair of double quotes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .