丢失了使用"echo -e"的格式.扑朔迷离 [英] Losing formatting using "echo -e" in bash
问题描述
以下代码段有问题:
while read line
do
team1=`echo "${line% *}"`
team2=`echo "${line#* }"`
newline=`printf "%-8.2f\t%-8.2f\n" "$team1" "$team2"`
#this line give perfect output
# echo "$newline"
##################problem is here########################
final_list=("${final_list[@]}" "$newline")
#########################################################
done <input.txt
#this line is losing all the formatting I gave
echo -e ${final_list[@]} | sort -t$'\t' -k1 -nr
这是我的输入文件
3.01 16.12
1.12 13.22
3.01 14.12
我的预期输出是
1.12 13.22
3.01 14.12
3.01 16.12
推荐答案
替换:
echo -e ${final_list[@]} | sort -t$'\t' -k1 -nr
具有:
printf "%s\n" "${final_list[@]}" | sort -t$'\t' -k1 -n
这可以达到您的预期输出:
This achieves your expected output:
$ printf "%s\n" "${final_list[@]}" | sort -t$'\t' -k1 -n
1.12 13.22
3.01 14.12
3.01 16.12
有两个必需的更改.首先, sort
逐行工作,而 echo
输出产生一行.其次,由于您所需的输出是按升序进行数字排序的,因此需要从 sort
中删除 -r
标志.
There were two required changes. First, sort
works line-by-line and the echo
output produces a single line. Second, because your desired output was numerically sorted in ascending order, the -r
flag needed to be removed from sort
.
此行不符合人们的想法:
This line does not do what one would think:
newline=`printf "%-8.2f\t%-8.2f\n" "$team1" "$team2"`
问题在于,当Shell执行命令替换时,所有尾随的换行符都会被删除.因此,在将输出分配给 newline
之前,将删除 printf
格式的 \ n
.
The problem is that, when the shell does command substitution, any trailing newline characters are deleted. So, the \n
in the printf
format is removed before the output is assigned to newline
.
这意味着当您到达此处:
That means that when you get to here:
echo -e ${final_list[@]}
没有换行符. echo
输出全部显示在一行上.
There are no newlines. The echo
output all appears on one line.
现在,考虑:
#this line give perfect output
# echo "$newline"
之所以可行,是因为 echo
在输出中添加了自己的换行符.
That works because echo
adds its own newline to the output.
我不知道您的大项目的结构,但是,作为所提供代码的一种可能替代方法,请考虑:
I don't know the structure of your big project, but, as a possible alternative to the code presented, consider:
while read team1 team2
do
newline=$(printf "%-8.2f\t%-8.2f" "$team1" "$team2")
final_list=("${final_list[@]}" "$newline")
done <input.txt
printf "%s\n" "${final_list[@]}" | sort -t$'\t' -k1 -n
仍然很简单,但在大型项目中可能无济于事,将是重新格式化和排序 input.txt
的代码:
Still simpler, but possibly not helpful in the big project, would be this code which reformats and sorts input.txt
:
$ awk '{printf "%-8.2f\t%-8.2f\n",$1,$2}' input.txt |sort -n
1.12 13.22
3.01 14.12
3.01 16.12
这篇关于丢失了使用"echo -e"的格式.扑朔迷离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!