AWK If/Else 条件问题
我有一个看起来像这样的数据:
foo foo scaffold_7 1 4845 6422 4845
bar bar scaffold_7 -1 14689 16310 16310
我想做的是处理上面的行 我只想打印第 1,2,3,7 列以及第 7 列之后的一列。 但在打印第 7 栏以后有条件。
下面是我的 awk 脚本:
awk '{
if ($4=="+") { {end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7 "\t" end+$7} }
else
{end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
}'
但为什么它没有达到这样的预期结果呢?
foo foo scaffold_7 1 4845 6422
bar bar scaffold_7 -1 14689 16310
请注意,算术运算(例如$7-end
或end+$7
)是必须的。所以我们不能只交换列 来自输入文件。此外,该 AWK 将位于 bash 脚本内。
I have a data that looks like this:
foo foo scaffold_7 1 4845 6422 4845
bar bar scaffold_7 -1 14689 16310 16310
What I want to do is to process the above lines
where I just want to print column 1,2,3, 7 and one more column after 7th.
But with condition when printing column 7 onwards.
Below is my awk script:
awk '{
if ($4=="+") { {end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7 "\t" end+$7} }
else
{end=$6-$5}{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
}'
But why it doesn't achieve the desired result like this?
foo foo scaffold_7 1 4845 6422
bar bar scaffold_7 -1 14689 16310
Note that the arithmetic (e.g. $7-end
or end+$7
) is a must. So we can't just swap column
from input file. Furthermore this AWK will be inside a bash script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
我从未在大括号内使用过大括号,并且更喜欢使用分号分隔符来实现此目的。我非常确定在您的示例中,else 子句仅绑定到
{end=$6-$5}
,而不是绑定到两个大括号条目。在这种情况下,{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
将为所有执行行。Try:
I've never used braces within braces and prefer the semi-colon separators for this purpose. I'm pretty certain the else clause is bound only to
{end=$6-$5}
in your example, not to both the braced entries. In that case,{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $7-end "\t" $7}
will be executed for all lines.或者将其压缩为一行而不重复
print
语句:or condense it to one-liner without repeating the
print
statement :