简体   繁体   中英

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.

With Perl.

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

Output to new.txt :

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

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'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM