文件示例
I have a 3-10 amount of files with:
- different number of columns
- same number of rows
- inconsistent spacing (sometimes one space, other tabs, sometimes many spaces) **within** the very files like the below
> 0 55.4 9.556E+09 33
> 1 1.3 5.345E+03 1
> ........
> 33 134.4 5.345E+04 932
>
........我需要从file1获取列(例如)1,从file2获取第3列,从file3获取第7列,从file4获取第1列,并将它们并排合并到一个文件中。
试用1:不工作
粘贴<(剪切-dsee低于-f1 file1) <(剪切-dsee低于-f3 file2) 其中分隔符是‘’或空的。
试用版2:处理2个文件,但不处理多个文件
awk '{ a1=$1;b1=$4;getline <"D2/file1.txt";打印a1,$1,b1,$4 }‘D1/file1.txt >D3/file1.txt
现在更普遍的问题是:
如何从许多不同的文件中提取不同的列?
发布于 2012-10-05 14:13:08
在您的paste / cut尝试中,将cut替换为awk:
$ paste <(awk '{print $1}' file1 ) <(awk '{print $3}' file2 ) <(awk '{print $7}' file3) <(awk '{print $1}' file4)发布于 2012-10-05 13:57:03
假设每个文件都有相同的行数,下面是使用GNU awk的一种方法。跑得像:
awk -f script.awk file1.txt file2.txt file3.txt file4.txtscript.awk含量
FILENAME == ARGV[1] { one[FNR]=$1 }
FILENAME == ARGV[2] { two[FNR]=$3 }
FILENAME == ARGV[3] { three[FNR]=$7 }
FILENAME == ARGV[4] { four[FNR]=$1 }
END {
for (i=1; i<=length(one); i++) {
print one[i], two[i], three[i], four[i]
}
}注意:
默认情况下,awk在空格上分隔列。这包括制表符字符和空格,以及其中的任意数量。这使得awk对于间距不一致的文件非常理想。如果您愿意,还可以展开上面的代码以包含更多文件。
发布于 2012-10-05 12:17:39
cut和paste的结合应该是可行的:
$ cat f1
foo
bar
baz
$ cat f2
1 2 3
4 5 6
7 8 9
$ cat f3
a b c d
e f g h
i j k l
$ paste -d' ' <(cut -f1 f1) <(cut -d' ' -f2 f2) <(cut -d' ' -f3 f3)
foo 2 c
bar 5 g
baz 8 k编辑:也适用于选项卡:
$ cat f4
a b c d
e f g h
i j k l
$ paste -d' ' <(cut -f1 f1) <(cut -d' ' -f2 f2) <(cut -f3 f4)
foo 2 c
bar 5 g
baz 8 khttps://stackoverflow.com/questions/12745834
复制相似问题