How to remove new lines in double quotes?

How to delete a new line inside "from a file?

For instance:

"one", 
"three
four",
"seven"

Therefore, I want to delete \nbetween threeand four. Should I use regex, or do I need to read this file to a character with a program?

+4
source share
5 answers

To process exactly those newline lines that are in double-quoted lines and leave them outside of them using GNU awk (for RT):

gawk -v RS='"' 'NR % 2 == 0 { gsub(/\n/, "") } { printf("%s%s", $0, RT) }' file

This works by breaking the file by characters "and deleting newlines in every other block. With file containing

"one",
"three
four",
12,
"seven"

it will give a result

"one",
"threefour",
12,
"seven"

, escape-. \", "He said: \"this is a direct quote.\"", .

+14

, ". , :

$ awk '/^"/ {if (f) print f; f=$0; next} {f=f FS $0} END {print f}' file
"one", 
"three four",
"seven"

, END .

+5

sed :

sed -r '/^"[^"]+$/{:a;N;/",/!ba;s/\n/ /g}' text

, , : /^"[^"]+$/

, :a , . N, . /",/!, a ba, .

, gettting s/\n/ /g, sed.

+1

bash

: \n

unix newline (\n), windows newline (\ r\n) mac newline (\n\r)

echo -e ' "line1\nline2" ' `

line1
line2

echo -e '"line1 \ nline2"' | gawk -v RS = '"' 'NR% 2 == 0 {gsub (/ \ r? \ n \ r? /," \ n ")} {printf ("% s% s ", $ 0, RT)}

line1\nline2

+1
source

The simplest solution:

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA>) {
    chomp;
    if (m/^\"/) { print "\n"; }
    print;
}


__DATA__
"one", 
"three
four",
"seven"

But, taking a specific case of style data csv, I would suggest using a perl module called Text::CSV, which parses CSV correctly, and processes the element with linefeed element of the previous line.

#!/usr/bin/perl

use strict;
use warnings;

use Text::CSV;

my $csv = Text::CSV->new( { binary => 1 } );

open( my $input, "<", "input.csv" ) or die $!;

while ( my $row = $csv->getline($input) ) {
    for (@$row) {
        #remove linefeeds in each 'element'. 
        s/\n/ /g;
        #print this specific element ('naked' e.g. without quotes). 
        print;
        print ",";
    }
    print "\n";
}
close($input);
0
source

All Articles