Replace tab inside double quotes as space Sed, Regexp

Viewed 68

Hello Sed/Regexp experts, Need some help,

I have a file with below contents, need to replace tabs as space inside double quotes. Note \t is tab.

1 \t 2 \t 3 \t "4 \t 5 \t 6" \t 7

Expected output:

1 \t 2 \t 3 \t "4 5 6" \t 7

Matching quotes and tired replacing the tabs to space but it replaces the content inside the quotes.

sed '/\s/s/".*"/"  "/' 1.txt

Thanks

4 Answers

Here is a sed solution using label:

sed -E -e :a -e 's/("[^\t"]*)\t([^"]*")/\1 \2/; ta' file

1    2   3   "4 5 6"   7

However, it is easier to do this using awk by using " as field delimiter and change every even numbered field (which will be inside the quote):

awk '
BEGIN {FS=OFS="\""}
{
   for (i=2; i<=NF; i+=2)
      gsub(/\t/, " ", $i)
} 1' file

1    2   3   "4 5 6"     7

With your shown samples Only, please try following awk code. Written and tested in GNU awk using RT variable of awk to deal with values between "....".

awk -v RS='"[^*]*"'  'RT{gsub(/\t/,OFS,RT);ORS=RT;print};END{ORS="";print}' Input_file

with python using indexes and regex - re.sub

st = r'1    2   3   "4  5   6"  7'

l_ind = st.index('"')
r_ind = st.rindex('"')

new_st = st[:l_ind] + re.sub(r'\s+', r' ', st[l_ind:r_ind]) + st[r_ind:]

1    2   3   "4 5 6"  7

another version using re.sub and re.findall

re.sub(r'".*?"',re.sub(r'\s+', r' ', re.findall(r'".*?"', st)[0]), st)

1    2   3   "4 5 6"  7
  • re.findall(r'".*?"', st)[0] - find the string in double quotes
  • re.sub(r'\s+', r' ', - compress the multiple space to one inside the double quoted string
  • re.sub(r'".*?"', - substitute the original double quoted string with the new one.

This might work for you (GNU sed):

sed -E ':a;s/^([^"]*("[^"\t]*"[^"]*)*"[^"\t]*)\t/\1 /;ta' file

Replace the first tab within matched double quotes with a space and repeat until failure.

N.B. This solution caters for lines with multiple matching double quotes.

Related