How can I remove new line inside the "
from a file?
For example:
"one",
"three
four",
"seven"
So I want to remove the \n
between the three
and four
. Should I use regular expression, or I have to read that's file per character with program?
Assuming you have no commas or newlines within your fields and all of your fields are double quoted as in your example then using any sed in any shell on every Unix box you could do: The double quote (s) we are after, will always have neighbors on both of its sides. And the neighbors will always be noncomma.
Replace "" with ",". s/" ( [0-9]*)",?/\1,/g : remove all quotes around numbers. So, while you can find a number that is right after a quote and followed by a comma and another number, join the two numbers together and repeat the process until it is no longer possible.
There a n number of numbers present within the double quotes separated by commas. And also leave the double quotes which contains characters as it is. I love sed text processing tool. I'm happy if you post any sed solution for this. Show activity on this post.
That’s way too many double quotes for the Scripting Guys to deal with. Therefore, we sidestep the problem of embedding quotes within quotes within quotes by, instead, searching for consecutive instances of Chr (34): As you might have guessed, Chr (34) is equivalent to the double quote mark: “.
To handle specifically those newlines that are in doubly-quoted strings and leave those alone that are outside them, using GNU awk (for RT
):
gawk -v RS='"' 'NR % 2 == 0 { gsub(/\n/, "") } { printf("%s%s", $0, RT) }' file
This works by splitting the file along "
characters and removing newlines in every other block. With a file containing
"one",
"three
four",
12,
"seven"
this will give the result
"one",
"threefour",
12,
"seven"
Note that it does not handle escape sequences. If strings in the input data can contain \"
, such as "He said: \"this is a direct quote.\""
, then it will not work as desired.
You can print those lines starting with "
. If they don't, accumulate its content into a variable and print it later on:
$ awk '/^"/ {if (f) print f; f=$0; next} {f=f FS $0} END {print f}' file
"one",
"three four",
"seven"
Since we are always printing the previous block of text, note the need of END
to print the last stored value after processing the full file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With