[英]Awk swap column and replace another column conditionally
我有看起來像這樣的數據
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
如果您的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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.