如何实现文件空白行后续行追加至前一行的文本处理需求?
Merge Lines After Blank Lines into the Preceding Line (No More Blank Lines)
Got it, let's tackle this text processing task: you need to process a file such that any blank line triggers merging the lines that follow it directly onto the end of the line right before the blank line, with all blank lines removed entirely. Your example makes this super clear, so let's dive into solutions.
Example Reference
Input content:
A B C 1 D E BProcessed output:
A B C 1D EB
Python Solution
This simple Python script will handle the task perfectly, and it's easy to adjust if your use case needs tweaks:
def merge_post_blank_lines(input_content): # Split content into lines, strip newline characters lines = [line.rstrip('\n') for line in input_content.splitlines()] merged_lines = [] just_saw_blank = False for line in lines: if not line: # We hit a blank line just_saw_blank = True continue if just_saw_blank: # Append this line to the last entry in our merged list merged_lines[-1] += line just_saw_blank = False else: merged_lines.append(line) # Join all merged segments into one final line (matches your example) return ''.join(merged_lines) # Test with your sample input sample_input = """A B C 1 D E B""" print(merge_post_blank_lines(sample_input)) # Output: A B C 1D EB
How This Works
- First, we split the input into individual lines and clean up newline characters.
- The
just_saw_blankflag tracks whether we just encountered a blank line—this tells us we need to append the next non-blank line to the previous one. - When we hit a blank line, we set the flag and move on (we don't keep blank lines at all).
- If the flag is active, we add the current line's text to the last line we saved instead of creating a new entry.
- Finally, we join all the merged pieces into a single string, just like your example shows.
Command-Line Alternative (awk)
If you'd rather use a shell command instead of a script, this awk one-liner does the same job:
awk 'NF { if (blank_seen) { printf "%s", $0; blank_seen=0 } else { printf "%s", $0 } } !NF { blank_seen=1 } END { print "" }' your_file.txt
NFchecks if a line is non-blank (has content).!NFchecks if a line is blank.- The
blank_seenflag tracks when we need to append the next line to the previous output. We useprintfinstead ofprintto avoid adding newlines between merged segments. - The
END { print "" }adds a final newline to the output for clean formatting.
内容的提问来源于stack exchange,提问作者user1485267
相关产品推荐
相关产品推荐

