问题描述
我有一个变量 ($var),其中包含一系列用逗号排序和分隔的数字。举个例子:
3,31,35,57,85,108,120,130,193,234,266,354,369,406,430,438,472,490,503,553,579,591,629,670,715,742,768,792,813
我最初的计划是通过下一个代码使用它们来提取文件 1 中的一系列列:
cat file1 | cut -f "$var"
终端警告我一个问题:“参数列表太长”。我的目标保持不变——我可以遵循哪种策略/替代方案?我需要一些可以让我获得所有列的东西(将它们保存或不保存在文件中)。使用循环或其他任何可能会阻止我“手动/单独”执行此操作。
所需输出的(较小)示例:
123 299 429
12 0 2
0 0 2
4 15 20
4 22 27
3 2 7
0 0 0
61 155 77
8327 5961 10023
5 11 17
5777 8840 5669
10 3 1
53 365 199
1 0 3
26 31 15
1 0 0
解决方法
假设:
- 您的
file1
包含大量由制表符分隔的列。 - 您想要选择列在 bash 变量“$var”中的列。
- 列表太长,无法作为命令行参数接受。
那么您会尝试awk
解决方案吗:
#!/bin/bash
var="3,31,35,57,85,108,120,130,193,234,266,354,369,406,430,438,472,490,503,553,579,591,629,670,715,742,768,792,813"
echo "$var" > list
# the "echo" command above is for the demonstration purpose only.
# please create a csv file "list" which contains the column list as "var".
awk '
BEGIN {FS = OFS = "\t"} # assign the field separators to TAB
NR==FNR {len = split($0,a,","); next} # read the file "list" and assign an array "a" to the list
{
result = $a[1] # 1st element of the column indexed by array a
for (i = 2; i <= len; i++) # loop over the column list
result = result OFS $a[i] # append the next element of the indexed column
print result # print the record
}
' list file1
我们需要将列号列表存储在单独的文件“列表”中以避免 Argument list too long
错误。我已经测试了大约。 600KB 列表,它可以工作。
使用awk:
awk -F,'{ print $4","$7 }' file1
在此示例中,我们将字段分隔符设置为 ,使用 -F,然后仅打印第 4 和第 7 字段/列。