首页 > 解决方案 > Awk swap column and replace another column conditionally

问题描述

i have data that looks like this

A 12 14 + aaa
B 16 19 + bbb
C 14 10 + ccc
D 9 20 + ddd
E 12 6 + eee

if $2 > $3, i want to swap $2 and $3 change $4 to "-". The end result should look like this:

A 12 14 + aaa
B 16 19 + bbb
C 10 14 - ccc
D 9 20 + ddd
E 6 12 - eee

i could do it with

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

But it looks messy and there definitely is a neater way to do it. Could someone more experienced in bash and awk enlighten me on the way?

标签: linuxawk

解决方案


请您尝试以下操作。

awk '$2>$3{tmp=$2;$2=$3;$3=tmp;$4="-"} 1' Input_file

如果您的 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.

推荐阅读