如何利用csplit拆分文本文件,并按指定字符串命名输出的多个文件?
Solution to Split Entries into Named Files
Since csplit doesn't support custom output filenames directly, here are two straightforward solutions using shell scripting and awk that will get the job done:
Option 1: Bash Script
Create a script (e.g., split_entries.sh) with the following content:
#!/bin/bash # Replace with your input file name INPUT_FILE="original_text_file.txt" current_output="" while IFS= read -r line; do # Check if we're starting a new entry if [[ "$line" == ">"* ]]; then # Extract the filename from the line (remove leading ">") current_output="${line#>}" # Write the header line to the new file (overwrites if exists) echo "$line" > "$current_output" # Check if we've reached the end of an entry elif [[ "$line" == "--" ]]; then # Reset the current output file current_output="" # If we're in the middle of an entry, append the line elif [[ -n "$current_output" ]]; then echo "$line" >> "$current_output" fi done < "$INPUT_FILE"
How to run:
- Save the script to a file (like
split_entries.sh) - Make it executable:
chmod +x split_entries.sh - Run it:
./split_entries.sh
This script reads your input file line by line:
- When it hits a line starting with
>, it creates a new file named after the text following>and writes the header line to it. - It appends subsequent lines to that file until it encounters a
--separator. - Existing files with the same names will be overwritten, so be cautious if you have files with those names already.
Option 2: Awk One-Liner
If you prefer a more concise approach, use this awk command directly in your terminal:
awk ' /^>/ { if (outfile != "") close(outfile); outfile = substr($0, 2); print > outfile; next; } /^--$/ { close(outfile); outfile = ""; next; } outfile != "" { print >> outfile; } ' original_text_file.txt
How it works:
- When a line starts with
>, it closes any open output file, sets the output filename to the text after>, and writes the header line to that file. - When it sees
--, it closes the current output file and stops writing to it. - For all other lines, if an output file is active, it appends the line to that file.
Both methods will generate the 5 files you need, each named exactly after the header string and containing the full entry including the header line.
内容的提问来源于stack exchange,提问作者Zez
相关产品推荐
相关产品推荐

