Fred
Fred

Reputation: 395

How to delete newline and character at the start of line using Bash?

I need to delete a newline with exact character at the beginning of the line.

For example, I have new.txt file which contains the following lines:

"AAA"AAA
"BBB
"""BBB
"CCC"CCC

Expected result is:

"AAA"AAA
"BBB"BBB
"CCC"CCC

I tried using sed but it is not working.

sed -i -e 's/\n"""/"/g' new.txt

Please help me to solve this.

Upvotes: 1

Views: 662

Answers (4)

TomasPokorny
TomasPokorny

Reputation: 13

With GNU sed:

$ cat new.txt
"AAA"AAA
"BBB
"""BBB
"CCC"CCC

$ sed ':x;N;s/\n""//;bx' new.txt
"AAA"AAA
"BBB"BBB
"CCC"CCC

GNU - sed manual - joining lines

T.

Upvotes: 0

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed 'N;s/\n"""/"/;P;D' file

Append the next line to the current line. If the pattern space now contains \n""" replace it by " and then print/delete the first line in the pattern space and repeat.

Upvotes: 0

Cyrus
Cyrus

Reputation: 88553

With Perl.

perl -i -0777pe 's/\n"""/"/' new.txt

Output to new.txt:

"AAA"AAA
"BBB"BBB
"CCC"CCC

Upvotes: 1

skboro
skboro

Reputation: 195

Use tr to replace the \r\n. Use the sed command and then replace the \r\n back. \r is there since your file has Windows line endings.

tr '\r' '\t' < new.txt | tr '\n' '\f' | sed -e 's/\t\f"""/"/' | tr '\f' '\n' | tr '\t' '\r'

Upvotes: 0

Related Questions