Removing spaces from strings contained in double quotes of a bash script

I used sep to try this, basically I have a text file that contains a reasonable amount of the same line, for example.

4444 username "some information" "someotherinformation" "even more information"

I need to replace the spaces inside the quotes with underscores so that they look like this:

4444 username "some_information" "someotherinformation" "even_more_information"

currently I have been able to highlight the cited information

sed 's/"\([^"]*\)"/_/g' myfile.txt

Advice on how to proceed?

+3
source share
4 answers
sed -r ':a; s/^((([^"]*"){2})*[^"]*"[^" ]*) /\1_/;ta'
4444 username "some_information" "someotherinformation" "even_more_information"

or

sed ':a; s/^\(\(\([^"]*"\)\{2\}\)*[^"]*"[^" ]*\) /\1_/;ta'
4444 username "some_information" "someotherinformation" "even_more_information"
  • :a - label "a" for the loop
  • s/// - perform a substitution
  • ^( - bind the entire search line at the beginning of the line
  • (([^"]*"){2})* - capture (in group 1) two sets of zero or more non-quotation marks followed by a quote (zero or more)
  • [^"]*" - followed by zero or more non-quotation marks, followed by a quote
  • [^" ]* - ,
  • ) -
  • \1 -
  • ta - () :a, ( , - , )

, . , , , . .

, ... ..

:a... ta:

4444 username "some information" "someotherinformation" "even_more information"

4444 username "some information" "someotherinformation" "even_more_information"

4444 username "some_information" "someotherinformation" "even_more_information"

, .

+6

EDITED

. , OP.

, , , .

awk -F'"' '
  BEGIN {
    OFS="\""
  }
  {
    for (i = 2; i < NF; i += 2) {
      gsub(/[ \t]+/, "_", $i)
    }

    print $0
  }
' file > outputFile
+3

C, , .

#include <stdio.h>
int main(void)
{
    int inside_quotes = 0;
    int backslash = 0;
    int c;
    while ((c = getchar()) != EOF) {
        switch (c) {
        case ' ':
            if (inside_quotes)
                c = '_';
            break;
        case '"':
            if (!backslash)
                inside_quotes = !inside_quotes;
            break;
        case '\\':
            if (!backslash)
                backslash = 2;
            break;
        default:
            break;
        }
        if (backslash > 0) backslash--;
        putchar(c);
    }
    return 0;
}

. , , .

0

:

echo '4444 username "some information" "someotherinformation" "even more information"' |
sed 's/"[^"]*"/\n&/g;:a;s/\(\n"[^"]*\) /\1_/g;ta;s/\n//g'
4444 username "some_information" "someotherinformation" "even_more_information"
  • (\n) . sed 's/"[^"]*"/\n&/g;
  • _. :a;s/\(\n"[^"]*\) /\1_/g;ta
  • . s/\n//g
0

All Articles