Linux Awk交换列并有条件地替换另一列

Linux Awk交换列并有条件地替换另一列,linux,awk,Linux,Awk,我有这样的数据 A 12 14 + aaa B 16 19 + bbb C 14 10 + ccc D 9 20 + ddd E 12 6 + eee 如果$2>$3,我想交换$2和$3,将$4改为“-”。最终结果应如下所示: A 12 14 + aaa B 16 19 + bbb C 10 14 - ccc D 9 20 + ddd E 6 12 - eee 我可以用它来做 awk -F "\t" '$2 > $3 {print $1 "\t" $3 "\t" $2 "\t" "-"

我有这样的数据

A 12 14 + aaa
B 16 19 + bbb
C 14 10 + ccc
D 9 20 + ddd
E 12 6 + eee
如果$2>$3,我想交换$2和$3,将$4改为“-”。最终结果应如下所示:

A 12 14 + aaa
B 16 19 + bbb
C 10 14 - ccc
D 9 20 + ddd
E 6 12 - eee
我可以用它来做

awk -F "\t" '$2 > $3 {print $1 "\t" $3 "\t" $2 "\t" "-" "\t" $5}' file1 > file2
awk -F "\t" '$3 > $2 {print $1 "\t" $2 "\t" $3 "\t" "+" "\t" $5}' file1 >> file2

但它看起来很凌乱,而且肯定有更整洁的方法。在bash和awk方面更有经验的人能在路上给我点化一下吗?

你能试试下面的吗

awk '$2>$3{tmp=$2;$2=$3;$3=tmp;$4="-"} 1' Input_file
如果您的输入文件是制表符分隔的,则在上述代码中添加
-F'\t'

说明:

awk '
$2>$3{     ##Checking condition if $2 is greater than $3 then do following.
  tmp=$2   ##Creating a variable tmp whose value is $2.
  $2=$3    ##Setting $3 value to $2 here.
  $3=tmp   ##Setting variable tmp value to $3 here.
  $4="-"   ##Setting $4 as - as per requirement.
}          ##Closing condition BLOCK here.
1          ##Mentioning 1  will print edited/non-edited lines, awk works on method of pattern and action, by mentioning 1 I am making pattern/condition as true and no action is mentioned so default print of line will happen.
' Input_file ##Mentioning Input_file name here.

你能试试下面的吗

awk '$2>$3{tmp=$2;$2=$3;$3=tmp;$4="-"} 1' Input_file
如果您的输入文件是制表符分隔的,则在上述代码中添加
-F'\t'

说明:

awk '
$2>$3{     ##Checking condition if $2 is greater than $3 then do following.
  tmp=$2   ##Creating a variable tmp whose value is $2.
  $2=$3    ##Setting $3 value to $2 here.
  $3=tmp   ##Setting variable tmp value to $3 here.
  $4="-"   ##Setting $4 as - as per requirement.
}          ##Closing condition BLOCK here.
1          ##Mentioning 1  will print edited/non-edited lines, awk works on method of pattern and action, by mentioning 1 I am making pattern/condition as true and no action is mentioned so default print of line will happen.
' Input_file ##Mentioning Input_file name here.

它起作用了!谢谢我必须添加OFS='\t',但除此之外,它工作得非常好。问题是,最后的1是做什么的?显然这是命令运行所必需的。@VillagerA,现在请检查我的解释。它运行了!谢谢我必须添加OFS='\t',但除此之外,它工作得非常好。问题是,最后的1是做什么的?显然这是命令运行所必需的。@VillagerA,现在请检查我的解释。