简体   繁体   中英

Append n lines up to a certain character in the previous line

Input:

[5 8 15 79 5 6  
.  
.  
.   
n 8 6 4 5 ]  
[18 78 18 79 5 6  
.  
.  
.   
n 8 6 78 ]

and so on...

Desired output:

[5 8 15 79 5 6 . . . . 8 6 4 5 ]  
[18 78 18 79 5 6 . . .  8 6 78 ]

I need to convert all the columns up to ] into a single line and keep on doing so up to the end of the file.

It sound like you just want to only print a newline if the current lines ends with ] . Try:

awk '{printf "%s%s", $0, match($0,"]\\s*$") ? "\n" : ""}' input

With sed:

$ sed ':a;N;/\]/!ba;s/\n//g' infile
[5 8 15 79 5 6  .  .  .   n 8 6 4 5 ]
[18 78 18 79 5 6  .  .  .   n 8 6 78 ]

Explained:

:a        # Label to jump to
N         # Append next line to pattern sapce
/\]/! ba  # If there is no "]", jump to label
s/\n//g   # Remove all newlines (only reached if "]" in pattern space)

If you want to make sure that ] is the last non-blank character on the line, not just anywhere in it, the regex can be changed from /\\]/ to /\\][[:blank:]]*$/ , resulting in

sed ':a;N;/\][[:blank:]]*$/!ba;s/\n//g' infile

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