排序以多部分项目的列表 [英] Sorting a list with multi-part items
本文介绍了排序以多部分项目的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第三次尝试了解什么林做错了。
Ive得到像这样的列表:
数组[0] = 1111这里是多的文本
阵列[1] = 2222下面是更文本
数组[2] = 1111.1下面是特殊的文本
现在我想对列表进行排序,以有这样的:
1111这里是多的文本
1111.1这里是特殊的文本
2222这里更是文本
使用
的j $ {数组[@]};做回声$焦耳;做| -n排序
它的方式隔开了我的每一个部分,因为空间的。
使用
在$ {数组[@]}j;不要回声$ J;做| -n排序
我得到一个排序列表像1111 2222 1111.1
解决方案
=数组(
1111这里是多的文本
2222这里更是文字
1111.1这里是特殊文本
)
printf的%S \\ n$ {数组[@]}| -n排序
1111这里是多的文本
1111.1这里是特殊的文本
2222这里更是文本
要保存它:
排序=()
而IFS =读-r线;做
分类+ =($线)
完成< ≤(printf的%S \\ n$ {数组[@]}|排序-n)
printf的%S \\ n$ {分类[@]}
如上#相同的输出
或
来源≤(回声'排序=('; printf的'%S\\ n$ {数组[@]}|排序-n;回声) )
printf的%S \\ n$ {分类[@]}
在你的文件会搞乱您回车。考虑名为T与DOS风格的行结束:
$猫-eŤ
一号线^ M $
2号线^ M $
3号线^ M $
$为N {1..3};做阵列[N] =$(回声$ N $(猫T)); DONE
$ printf的%S \\ n$ {数组[@]}| OD -C
0000000 1 L I否E 1 \\ R L I N e 2的\\ r
0000020升I N E 3 \\ r \\ N 2 L I否E 1 \\ r
0000040升我否E 2 \\ R L I N E 3 \\ r \\ n 3
0000060升我否E 1 \\ R L I N e 2的\\ R L我
0000100否E 3 \\ r \\ n
0000105
$ printf的%S \\ n$ {数组[@]}
line31
line31
line31
显然,这会搞砸了任何你这个输入馈。修复回车。
third try to understand what Im doing wrong.
Ive got a list like this:
array[0] = 1111 Here is much text
array[1] = 2222 Here is even more text
array[2] = 1111.1 Here is special text
Now I want to sort the list to have it like this:
1111 Here is much text
1111.1 Here is special text
2222 Here is even more text
Using
for j in ${array[@]}; do echo $j; done | sort -n
it seperates me every single part because of the spaces.
Using
for j in "${array[@]}"; do echo "$j"; done | sort -n
I get a sorted list like 1111 2222 1111.1
解决方案
array=(
"1111 Here is much text"
"2222 Here is even more text"
"1111.1 Here is special text"
)
printf "%s\n" "${array[@]}" | sort -n
1111 Here is much text
1111.1 Here is special text
2222 Here is even more text
To save it:
sorted=()
while IFS= read -r line; do
sorted+=("$line")
done < <( printf "%s\n" "${array[@]}" | sort -n )
printf "%s\n" "${sorted[@]}"
# same output as above
or
source <( echo 'sorted=('; printf '"%s"\n' "${array[@]}" | sort -n; echo ')' )
printf "%s\n" "${sorted[@]}"
Carriage returns in your file will mess you up. Consider file named "t" with dos-style line endings:
$ cat -e t
line1^M$
line2^M$
line3^M$
$ for n in {1..3} ; do array[n]="$(echo $n $(cat t))"; done
$ printf "%s\n" "${array[@]}"|od -c
0000000 1 l i n e 1 \r l i n e 2 \r
0000020 l i n e 3 \r \n 2 l i n e 1 \r
0000040 l i n e 2 \r l i n e 3 \r \n 3
0000060 l i n e 1 \r l i n e 2 \r l i
0000100 n e 3 \r \n
0000105
$ printf "%s\n" "${array[@]}"
line31
line31
line31
Clearly this is going to mess up anything you feed with this input. Fix the carriage returns.
这篇关于排序以多部分项目的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文