如何使用sed提取每第2行并将每两行存入指定新文件?
Got it, let's solve this step by step using sed (plus a few standard shell tools where needed—pure sed alone can't easily split output into multiple files without some tricky workarounds).
First: Extract Every 2nd Line from main.txt
To pull all even-numbered lines (line 2, 4, 6, etc.) from your file, use this straightforward sed command:
sed -n '2~2p' main.txt
Here's the breakdown of what each part does:
-n: Tells sed not to print every line by default (we only want to output specific lines).2~2p: The pattern means "start at line 2, then every 2 lines after that, print the line".
Second: Split Those Extracted Lines into file1.txt, file2.txt, file3.txt
There are two common ways to distribute the lines, depending on your exact needs:
Option 1: Cycle lines through the three files (e.g., line 1 → file1, line2→file2, line3→file3, line4→file1, etc.)
If you want to spread the extracted lines evenly across the three files, combine sed with bash process substitution to split the output into three separate sed processes:
sed -n '2~2p' main.txt | tee >(sed -n '1~3p' > file1.txt) >(sed -n '2~3p' > file2.txt) | sed -n '3~3p' > file3.txt
How this works:
- The first sed command extracts all even lines from
main.txt. teesends that output to three destinations:>(sed -n '1~3p' > file1.txt): Captures every 3rd line starting at line 1 and saves it tofile1.txt.>(sed -n '2~3p' > file2.txt): Captures every 3rd line starting at line 2 and saves it tofile2.txt.- The remaining output goes to the final sed command, which captures every 3rd line starting at line3 and saves it to
file3.txt.
Option 2: Split into chunks of 2 lines per file (first 2 lines → file1, next 2→file2, next2→file3, repeat)
If you want each file to hold consecutive pairs of the extracted lines, use split (a standard shell tool) alongside sed:
# Extract even lines and split into 2-line chunks sed -n '2~2p' main.txt | split -l 2 -d --additional-suffix=".txt" - temp_file # Rename the split files to your desired names mv temp_file00 file1.txt mv temp_file01 file2.txt mv temp_file02 file3.txt
Key flags for split:
-l 2: Split the input into files with 2 lines each.-d: Use numeric suffixes instead of alphabetic ones.--additional-suffix=".txt": Add.txtto the end of each split file.- temp_file: Use "temp_file" as the prefix for the split files before renaming.
If you strictly need a pure sed solution (no external tools like split), let me know—I can share a more verbose version that handles the splitting entirely with sed.
内容的提问来源于stack exchange,提问作者Drsin

