1

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"

"UDP_netprobe"
"ACL_allow"
"ACL_deny" 
1
  • 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

4

With perl:

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

With sed

sed -E ':A;s/("[^ "]+) ([^"]*")/\1_\2/;tA' infile
2
  • 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
1

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)
    print
}' <<END
first "UDP netprobe" hello
second "ACL allow" friendly "oops, another quoted field"
third "ACL deny" world
END
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
2
  • | 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
1

Using sed:

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

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

1
  • Did not work for me.
    – unxnut
    May 23, 2018 at 13:01
1
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 .