awk 脚本在特定行打印信息
我有一些数据文件,我需要提取一些信息。我想使用一个 awk 脚本来获取数据,这样我就可以将一些数据吸入 bash 数组中。
为此,我们假设我需要以下内容(1 索引): - 我需要 awk 打印第一列的第 2、3 和 4 行 - 我需要 awk 在第 8 行及以上打印第 1、2 和 3 列。但我希望所有的列在第二列之前打印,第二列在第三列之前打印。
使用以下数据示例:
abc
def
ghi
jkl
mno
1a1
2b2
11 22 33 44
55 66 77 88
99 00 12 13
14 15 16 17
我希望 awk 打印字符串:
def ghi jkl 11 55 99 14 22 66 00 15 33 77 12 16
我创建了以下内容,我认为它可以工作,但我收到一条错误消息“END bocks 必须有一个操作部分”。
awk '
BEGIN {i=0;}
{
if ((NR >= 2) && (NR <= 4))
print $1;
if (NR >= 8)
{
col1_arr[i] = $1;
col2_arr[i] = $2;
col3_arr[i] = $3;
i++;
}
}
END
{
for (j = 0; j < i; j++)
print col1_arr[j];
for (j = 0; j < i; j++)
print col2_arr[j];
for (j = 0; j < i; j++)
print col3_arr[j];
}' /path/to/my/file
提前致谢。
i have some data files, and i need to pull some info out. i'd like to use a single awk script to get data out, so i can suck some data into bash arrays.
for this, let's assume i need the following (1-indexed):
- i need awk to print column one on lines 2, 3, and 4
- i need awk to print columns 1, 2, and 3 on lines 8 and over. but i want all of the column ones printed before the column twos, and the column twos before the column threes.
using the following data example:
abc
def
ghi
jkl
mno
1a1
2b2
11 22 33 44
55 66 77 88
99 00 12 13
14 15 16 17
i would want awk to print the string:
def ghi jkl 11 55 99 14 22 66 00 15 33 77 12 16
i created the following, which i thought would work, but i am getting an error saying "END bocks must have an action part".
awk '
BEGIN {i=0;}
{
if ((NR >= 2) && (NR <= 4))
print $1;
if (NR >= 8)
{
col1_arr[i] = $1;
col2_arr[i] = $2;
col3_arr[i] = $3;
i++;
}
}
END
{
for (j = 0; j < i; j++)
print col1_arr[j];
for (j = 0; j < i; j++)
print col2_arr[j];
for (j = 0; j < i; j++)
print col3_arr[j];
}' /path/to/my/file
thanks ahead of time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效 -
This should work -
有点冗长。但这很好,如果你想保留它,它就可以维护。
每个 awk 规则是:
任一可以为空:
Empty或 Empty表示匹配每一行。
空<动作>表示打印(打印当前行)。
当然END没有行,因此打印变得毫无意义。
你所拥有的是:
你需要做的就是把动作和结束放在同一行。
您遇到的另一个问题是 print 在它打印的字符串上添加了换行符。
要解决此问题,请使用
printf("", Variables);
Slightly verbose. But that's fine it makes it maintainable if you want to keep it.
Each awk rule is:
Either may be empty:
Empty <Match> means match every line.
Empty <Action> means print (which prints the current line).
Of course END has no line so print becomes meaningless.
What you have is:
What you need to do is put the action on the same line as the end.
The other problem you are having is that print puts a newline onto the string it prints.
to get around this use
printf("<format string>", variables);
下面的 awk 行应该为您完成这项工作:
用您的示例进行测试:
输出
the awk line below should do the job for you:
test with your example:
output