Bash 使用“丢失格式”;回声-e“;在狂欢节上
我对以下代码段有问题:Bash 使用“丢失格式”;回声-e“;在狂欢节上,bash,shell,Bash,Shell,我对以下代码段有问题: 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
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
我的预期产出是
1.12 13.22
3.01 14.12
3.01 16.12
使用sort-n对文件进行排序(如果需要,将其重定向到新文件,如>newfile.txt并使用它) 替换:
echo -e ${final_list[@]} | sort -t$'\t' -k1 -nr
与:
这将实现您的预期输出:
$ printf "%s\n" "${final_list[@]}" | sort -t$'\t' -k1 -n
1.12 13.22
3.01 14.12
3.01 16.12
需要进行两项更改。首先,sort
逐行工作,echo
输出产生一行。其次,由于所需的输出是按升序进行数字排序的,因此需要从排序中删除-r
标志
出了什么问题
这句话不符合人们的想法:
newline=`printf "%-8.2f\t%-8.2f\n" "$team1" "$team2"`
问题是,当shell执行命令替换时,任何尾随的换行符都会被删除。因此,printf
格式中的\n
在将输出分配给换行符之前被删除
这意味着当你来到这里:
echo -e ${final_list[@]}
没有新行。echo
输出全部显示在一行上
现在,考虑一下:
#this line give perfect output
# echo "$newline"
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
这是因为echo
在输出中添加了自己的换行符
更简单的脚本
我不知道您的大项目的结构,但是,作为所提供代码的可能替代方案,请考虑:
#this line give perfect output
# echo "$newline"
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
如果您实际使用的是bash
,那么echo
在您的作业中是不必要的:team1=${line%*}
,同样对于team2
@chepner谢谢您,更合理的做法是final_list=(“${final_list[@]}”$newline”)
可以写成final_list+=(“$newline”)
。谢谢,它工作起来很有魅力,我拼命地发布问题,经过漫长的夜晚试图获得输出,所以只需自己编写代码并回答,而不运行代码,我也失去了%-8.2f,我不再是了。我按照我的计划B那样做了,但我认为读和写会让我的代码变慢。
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
$ 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