gpt4 book ai didi

awk - 使用 awk 将列附加到文件

转载 作者:行者123 更新时间:2023-12-04 21:12:03 24 4
gpt4 key购买 nike

我有一个有点长的 awk 脚本,我想在文件的“右侧”附加两列。我正在处理以下文件:

Node    temporary_Temperature   steady_Temperature  temporary_Sight steady_Sight    
1 x x - -
2 x x - -
3 - - - -
4 - - - -
5 x x x -
6 - - - -
7 - - - -
8 - - - -
9 - - - -
10 - - - -
11 - - - -
12 - - - -
13 x x - -
14 x x - -
15 x - - -
16 - - - -

数据已经写入文件,我想使用 awk 迭代此文件中的行,比方说,再追加两列。在标题行,我想附加列 foobar,然后将 x- 附加到每个列行取决于其他东西。我怎样才能做到这一点?由于我正处于较长脚本的中间,所以我不想使用 sed 除非有某种方法可以从 awk 脚本中调用 sed 并打印到同一文件?

最佳答案

您在这里可能遇到的问题是,每当 awk 修改字段时,它都会重新写入您的 $0,将 IFS 替换为 OFS。如果您的 FS 是“任意数量的空白”(默认 FS),并且它被替换为“空格”(默认 OFS),您将丢失格式。

演示:

[ghoti@pc ~]$ printf 'one    two\tthree\n'
one two three
[ghoti@pc ~]$ printf 'one two\tthree\n' | awk '{$4 = "four"} 1'
one two three four

如果您真的不想修改每一行的字段,而只想附加一个字符串,则无需重写字段分隔符即可:

[ghoti@pc ~]$ printf 'one    two\tthree\n' | awk '{print $0 "\tfour"}'
one two three four

在没有看到您的脚本或您想要附加的数据类型的情况下,我很难提供我知道适用于您的情况的具体示例,但这里有一个可以帮助您入门的示例:

  NR == 1 {
print $0 "\tfoo\tbar";
next;
}
{
print $0 "\t" (conditionone ? "x" : "-") "\t" (conditiontwo ? "x" : "-");
}

如果您在制定条件方面需要帮助,请将其包含在您的问题中。我在上面的代码中使用了缩写形式;您显然可以使用 printf() 将内容分隔开并进行多行打印,或者根据要包含在 print 中的两个条件设置变量。

作为替代方案,您可以在浏览输入数据时重新设置格式。例如(假设您问题中的尾随空格确实是您的输入文件的样子):

BEGIN {
fmt="%-20s%-20s%-20s%-20s%-20s%-20s%s\n";
}

NR == 1 {
printf("%s%12s%-20s%-20s\n", $0, " ", "foo", "bar");
next;
}

{ foo="-"; bar="-"; }

conditionone { foo="x"; }
conditiontwo { bar="x"; }

{
printf(fmt, $1, $2, $3, $4, $5, foo, bar);
}

您可能不得不调整第 1 行的间距。

关于awk - 使用 awk 将列附加到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14754484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com