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" 
  • 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). – αғsнιη May 23 '18 at 17:16
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
  • | 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 '18 at 12:37
  • sure, but there's no need for the extra test if you know you only want every 2nd field. – glenn jackman May 23 '18 at 12:38
4

With perl:

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

With sed

sed -E ':A;s/("[^ "]+) ([^"]*")/\1_\2/;tA' infile
  • This is the answer – harish2704 May 27 at 13:00
1

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 '18 at 13:01
1
sed 's/\(\"[^" ]*\) \([^"]*\"\)/\1_\2/g' file

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

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.