在Bash中将单行文本中每第3个逗号替换为换行符
Got it, let's fix this single-line CSV by splitting it into proper rows every 3 fields (replacing every 3rd comma with a newline). Here are a few reliable methods using common tools:
Using sed (Unix/Linux/macOS)
This uses extended regular expressions to match groups of 3 fields and replace the trailing comma with a newline:
sed -E 's/(([^,]+,){2}[^,]+),/\1\n/g' input.txt
-Eenables extended regex (avoids escaping parentheses on most systems)- The regex
(([^,]+,){2}[^,]+)captures a full set of 3 fields (e.g.,Name,Age,Year) - We replace the comma immediately after this group with a newline (
\n), and apply this globally (g)
Using awk
Awk makes it easy to loop through fields and print them in chunks:
awk -F, '{ for(i=1; i<=NF; i++) { printf "%s", $i if (i % 3 == 0 && i < NF) printf "\n" else if (i < NF) printf "," } print "" }' input.txt
-F,sets the field separator to a comma- We loop through each field, printing it followed by either a comma (for non-ending fields in a chunk) or a newline (after every 3rd field)
- The final
print ""adds a trailing newline to the output
Using Python
If you prefer a script-based approach, Python is straightforward:
# Read the input file with open("input.txt", "r") as f: content = f.read().strip() # Split into individual fields fields = content.split(',') # Print every 3 fields as a single line for i in range(0, len(fields), 3): print(','.join(fields[i:i+3]))
- This reads the entire line, splits it into a list of fields, then joins every 3 fields back into a comma-separated line and prints it
Testing with your sample input
Input line:
Name,Age,Year,Michael,27,2018,Carl,19,2018
Output from any of the above methods:
Name,Age,Year Michael,27,2018 Carl,19,2018
内容的提问来源于stack exchange,提问作者MJCS
相关产品推荐
相关产品推荐

