[英]How to use awk to print columns in a loop?
I have a multiple-column text output from some command, and want to print the columns one at a time, like: 我有一个命令的多列文本输出,并希望一次打印一列,如:
#!/usr/bin/ksh
typeset -i i=0
while [[ $i -lt 5 ]]; do
<command 1> |awk '{print $i}' |<command 2>
i=$i+1
done
I know $i
is not the way to specify the i-th column in awk. 我知道$i
不是在awk中指定第i列的方法。 What is the correct usage here? 这里的正确用法是什么?
Say, the output from command 1
is something like: 比如, command 1
的输出类似于:
"abc" "def" "ghi" "jkm"
"123" "456" "789" "0ab"
"erf" "fad" "dae" "kjh"
The value is not necessarily 3-character long. 该值不一定是3个字符长。 Here is just for example. 这只是一个例子。
I want to get the 1st column to the 4th column in turn, to be used by command 2
. 我想依次将第1列放到第4列,由command 2
。
You are getting confused between $i
the shell variable and $i
the i th field in awk
. 你在$i
shell变量和$i
在awk
第 i 个字段之间感到困惑。 You need to pass in the value of shell variable to awk
in using -v
: 你需要在使用-v
将shell变量的值传递给awk
:
#!/bin/bash
for i in {1..5}; do
<command1> | awk -v i="$i" '{print $i}' | <command2>
done
This will let command2
process each column from the output of command1
separately. 这将让command2
处理command1
输出中的每一列。
I won't do the loop in your question. 我不会在你的问题中做循环。 because, this will execute same command ( command 1
) n times ( 12 times in your example), just for extracting a value. 因为,这将执行相同的命令( command 1
) n次(在您的示例中为12次),仅用于提取值。 If the command 1
is expensive, your script would be slow. 如果command 1
很昂贵,那么你的脚本会很慢。 even if it is not expensive, it is not good practice, we should not do it like that. 即使它不贵,也不是好的做法,我们不应该这样做。
I would suggest you execute cmd1 only once, and then convert the output of it into a format, which is easy to pass to commnd2. 我建议您只执行一次cmd1,然后将其输出转换为格式,这很容易传递给commnd2。 for example: 例如:
OUT1=$(command1||awk '{for (i=1;i<=4;i++)print $i}')
this will turn the output into each col in a line, like: 这会将输出转换为一行中的每个col,如:
"abc"
"def"
"ghi"
"jkm"
"123"
"456"
"789"
"0ab"
"erf"
"fad"
"dae"
"kjh"
then you could work on the variable $OUT1
with loop or whatever. 然后你可以使用循环或其他任何东西来处理变量$OUT1
。
It is also possible to invoke the command2
within awk. 也可以在awk中调用command2
。 it depends on the requirement. 这取决于要求。 if you don't want to catch output of cmd2, you could do: 如果你不想捕获cmd2的输出,你可以这样做:
$(command1||awk '{for (i=1;i<=4;i++)system("command2 "$i)}')
But again, this is depended on your logic/requirement. 但同样,这取决于您的逻辑/要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.