how delete space in blank only between " " with bash

Viewed 162

txt with this format

"service blabla 1"                   5.456
"service blabla 2"                   456

i need remove space in blank only between " "

"serviceblabla1"                   5.456
"serviceblabla2"                   456

i have this command

sed 's/ //g'

result:

"serviceblabla2"456
6 Answers

In GNU awk with shown samples, please try following awk code.

awk -v RS='"[^"]*"' '{gsub(/[[:space:]]+/,"",RT);ORS=RT} 1' Input_file

Explanation: Setting RS as "[^"]*" to get values from " till next occurrence of ". Then removing spaces in its value to match OP's requirement. Finally printing the line.

Above code will print data on terminal, in case you want to inplace save into Input_file, then try following command.

awk -v RS='"[^"]*"' '{gsub(/[[:space:]]+/,"",RT);ORS=RT} 1' Input_file > temp && mv temp Input_file

You can use perl here:

perl -i -pe 's{"[^"]*"}{$&=~s|\s+||gr}ge' file

Note that -i will replace the text inline.

The "[^"]*" pattern will match any substrings in between the closest double quotation marks and $&=~s|\s+||gr willl remove all chunks of one or more whitespace chars inside the matches only.

See an online demo:

#!/bin/bash
s='"service blabla 1"                   5.456
"service blabla 2"                   456'
perl -pe 's{"[^"]*"}{$&=~s|\s+||gr}ge' <<< "$s"

Output:

"serviceblabla1"                   5.456
"serviceblabla2"                   456

With GNU awk for the 3rd arg to match():

$ awk 'match($0,/("[^"]*")(.*)/,a){gsub(/ /,"",a[1]); print a[1] a[2]}' file
"serviceblabla1"                   5.456
"serviceblabla2"                   456

or FPAT:

$ awk -v FPAT='"[^"]*"| .*' '{gsub(/ /,"",$1); print $1 $2}' file
"serviceblabla1"                   5.456
"serviceblabla2"                   456

You can use a small loop:

sed -r ':a; s/ (.*")/\1/;ta' file

Your sed command was close but you requested a global substitution which did not give your desired output.

Splitting the sed command to address the individual spaces with the same command would have worked.

sed 's/ //2;s/ //' $file

The will remove the first and second occurence of space.

Output

"serviceblabla1"                   5.456
"serviceblabla2"                   456

This code will only work on the first two spaces.

You can use this awk

awk '{gsub(/ /,"",$2)}1' OFS=\" FS=\" file
"serviceblabla1"                   5.456
"seryviceblabla2"                   456

Split the line by ", replace space in second filed with nothing.

Related