awk从文件中读取特定列 [英] awk to read specific column from a file
问题描述
我有一个小问题,希望能帮助我解决这个问题.
I have a small problem and I would appreciate helping me in it.
总而言之,我有一个文件:
In summary, I have a file:
1,5,6,7,8,9
2,3,8,5,35,3
2,46,76,98,9
我需要从中读取特定行并将其打印到另一个文本文档中.我知道我可以使用( awk'{print"$ 2""$ 3"}'
)彼此相邻地打印第二和第三列.但是,我需要使用两个语句作为( awk'{print"$ 2"}'>> file.text
)然后是( awk'{print"$ 3"}''>> file.text
),但这两列将显示在彼此下方而不是彼此相邻.
I need to read specific lines from it and print them into another text document. I know I can use (awk '{print "$2" "$3"}'
) to print the second and third columns beside each other. However, I need to use two statement as (awk '{print "$2"}' >> file.text
) then (awk '{print "$3"}' >> file.text
), but the two columns would appear under each other and not beside each other.
如何使它们并排出现?
推荐答案
如果您必须在单独的过程中提取列,请使用 粘贴
将它们缝合在一起.我假设您的shell是bash/zsh/ksh,并且我假设示例输入中的空白行不应该存在.
If you must extract the columns in separate processes, use paste
to stitch them together. I assume your shell is bash/zsh/ksh, and I assume the blank lines in your sample input should not be there.
paste -d, <(awk -F, '{print $2}' file) <(awk -F, '{print $3}' file)
产生
5,6
3,8
46,76
没有流程替代项:
awk -F, '{print $2}' file > tmp1
awk -F, '{print $3}' file > tmp2
paste -d, tmp1 tmp2 > output
根据您的答案进行更新:
Update based on your answer:
初次出现时,这是一个令人困惑的设置.这行得通吗?
On first appearance, that's a confusing setup. Does this work?
for (( x=1; x<=$number_of_features; x++ )); do
feature_number=$(sed -n "$x {p;q}" feature.txt)
if [[ -f out.txt ]]; then
cut -d, -f$feature_number file.txt > out.txt
else
paste -d, out.txt <(cut -d, -f$feature_number file.txt) > tmp &&
mv tmp out.txt
fi
done
那必须多次读取file.txt文件.显然,只需要阅读一次就会更有效:
That has to read the file.txt file a number of times. It would clearly be more efficient to only have to read it once:
awk -F, -f numfeat=$number_of_features '
# read the feature file into an array
NR==FNR {
colno[++i] = $0
next
}
# now, process the file.txt and emit the desired columns
{
sep = ""
for (i=1; i<=numfeat; i++) {
printf "%s%s", sep, $(colno[i])
sep = FS
}
print ""
}
' feature.txt file.txt > out.txt
这篇关于awk从文件中读取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!