You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash按分隔符截取文件字符串后输出格式异常求助

Fixing the Newline Issue in Your Bash Text Processing Script

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',' tells awk to use commas as the field separator.
  • printf outputs the fields in your desired order ($2, $4, $5, $3, $1) separated by spaces, and doesn't add a newline after each line (unlike print).
  • All output gets written directly to new.txt as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:11:36