Bash按分隔符截取文件字符串后输出格式异常求助
Hey there! Let's tackle that newline problem you're facing with your Bash script. I'll break down what's going wrong and show you a couple of easy fixes.
What's Causing the Newline Problem?
When you use cut to extract columns from your file, each variable ($a, $b, etc.) ends up containing the extracted values with the original newline characters from file.txt. When you use paste to combine these variables, it matches up lines from each input—so you end up with one converted line per original line in new.txt, instead of all content merged into a single line.
Solution 1: Use awk (Simpler & More Efficient)
awk is perfect for this kind of text manipulation—it can handle reordering fields and outputting everything in one line in a single command:
awk -F',' '{printf "%s %s %s %s %s ", $2, $4, $5, $3, $1}' file.txt > new.txt
Here's what this does:
-F','tellsawkto use commas as the field separator.printfoutputs the fields in your desired order ($2,$4,$5,$3,$1) separated by spaces, and doesn't add a newline after each line (unlikeprint).- All output gets written directly to
new.txtas a single continuous line.
If you want to remove the extra trailing space at the end of the line, pipe the output to sed:
awk -F',' '{printf "%s %s %s %s %s ", $2, $4, $5, $3, $1}' file.txt | sed 's/ $//' > new.txt
Solution 2: Modify Your Existing Script
If you want to stick with your original approach, you just need to remove the newlines from the final paste output. Update your script like this:
#!/bin/bash FILE=file.txt a=$(cut -d',' -f2 $FILE) b=$(cut -d',' -f4 $FILE) c=$(cut -d',' -f5 $FILE) d=$(cut -d',' -f3 $FILE) e=$(cut -d',' -f1 $FILE) # Combine fields and remove all newlines paste <(echo "$a") <(echo "$b") <(echo "$c") <(echo "$d") <(echo "$e") --delimiters ' ' | tr -d '\n' > new.txt
The tr -d '\n' command strips out all newline characters from the paste output, merging everything into one line.
Either of these methods will give you the single-line output you're looking for: 2 4 5 3 1 7 9 10 8 6 12 14 15 13 11...
内容的提问来源于stack exchange,提问作者beginner17

