Bash 按给定顺序对文件行重新排序

Bash 按给定顺序对文件行重新排序,bash,file-io,Bash,File Io,我有一个包含n行的文档a。我还有一个由n个整数组成的序列,所有这些整数都是唯一的,单向的(虽然对于大文件来说不是有效的): 如果您的文件很大,您可以使用此文件: $ seq='2,0,1' $ x=$(echo $seq | awk '{printf "%dp;", $0+1;print $0+1> "tn.txt"}' RS=,) $ sed -n "$x" file | awk 'NR==FNR{a[++i]=$0;next}{print a[$0]}' - tn.txt 第2行准备

我有一个包含n行的文档a。我还有一个由n个整数组成的序列,所有这些整数都是唯一的,单向的(虽然对于大文件来说不是有效的):

如果您的文件很大,您可以使用此文件:

$ seq='2,0,1'
$ x=$(echo $seq | awk '{printf "%dp;", $0+1;print $0+1> "tn.txt"}' RS=,)
$ sed -n "$x" file | awk 'NR==FNR{a[++i]=$0;next}{print a[$0]}' - tn.txt

第2行准备sed命令打印指令,然后在第3行中与sed命令一起使用。这只打印序列中的行号,而不按序列的顺序打印。awk命令用于根据顺序对sed结果排序。

将文件读入数组,然后使用索引功能:

echo "Enter the input file name"
read ip

index=0

while read line ; do
        NAME[$index]="$line"
            index=$(($index+1))
            done < $ip

echo "Enter the file having order"
read od

while read line ; do
        echo "${NAME[$line]}";
            done < $od

awk oneliner可以完成以下任务:

 awk -vs="$s" '{d[NR-1]=$0}END{split(s,a,",");for(i=1;i<=length(a);i++)print d[a[i]]}'  file
另一个解决方案:

您可以通过以下操作创建序列文件(假设序列以逗号分隔):

那么,只要做:

paste seq.txt A.txt | sort tmp2.txt | sed "s/^[0-9]*\s//"

这里有一个bash函数。顺序可以用任何东西来分隔

用法:
schwartzianttransform“A.txt”2 0 1

函数施瓦茨变换{
本地文件=“$1”
转移
本地序列=“$@”
echo-n“$sequence”| sed的/[^[:digit:][^[:digit:][]*/\
/g'| paste-d'-“$file”| sort-n | sed's/^[:digit:][]*/'
}

是不是应该是
Bar,Bat,Foo
还是我遗漏了什么?@axiom实际上我理解这样的问题:
Foo应该到位置2
Bar应该到位置0
Bat应该到位置1
。我需要更多的咖啡:)首先我想说,这很有效。但是它会遍历文件,整个文件
n
次,每次只打印一行。如果文件很大,那会很痛苦。我建议你在午休前启动这个命令。还有改进的余地。@Kent我现在实际上使用了一个简短的python脚本,因为我需要一个即时的解决方案,我只是认为应该有一个标准的unix工具专门为这项工作而设计。显然没有。在其他名称中,这是一个。这是最接近我想要的。谢谢
echo "Enter the input file name"
read ip

index=0

while read line ; do
        NAME[$index]="$line"
            index=$(($index+1))
            done < $ip

echo "Enter the file having order"
read od

while read line ; do
        echo "${NAME[$line]}";
            done < $od
[aman@aman sh]$ cat test 
Foo
Bar
Bat
[aman@aman sh]$ cat od
2
0
1
[aman@aman sh]$ ./order.sh 
Enter the input file name
test
Enter the file having order
od
Bat
Foo
Bar
 awk -vs="$s" '{d[NR-1]=$0}END{split(s,a,",");for(i=1;i<=length(a);i++)print d[a[i]]}'  file
kent$  seq 10 >file  #get a 10 lines file

kent$  s=$(seq 0 9 |shuf|tr '\n' ','|sed 's/,$//') # get a random sequence by shuf

kent$  echo $s     #check the sequence in var $s
7,9,1,0,5,4,3,8,6,2 

kent$  awk -vs="$s" '{d[NR-1]=$0}END{split(s,a,",");for(i=1;i<=length(a);i++)print d[a[i]]}'  file                                                                          
8
10
2
1
6
5
4
9
7
3
echo $sequence | sed s/,/\\n/g > seq.txt
paste seq.txt A.txt | sort tmp2.txt | sed "s/^[0-9]*\s//"