awk代码解释:更改字段顺序

Awk code explanation: changing order of fields

我有一个包含 14 列的 .txt 文件。它的头部看起来像这样:

name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi rsid
SNP1  A  T 0.05   1       5  56 7    8    9    11  12  rs1
SNP2  T  A 0.05   1       6  55 7    8    9    11  12  rs2

我想把最后一列放在第一个位置。我不确定这样做最有效的方法是什么,但我遇到了这个,从其他帖子中启发了自己:

awk '{[=11=]=$NF FS[=11=]; =""}1' file.txt | head

我得到了这个,我认为它有效:

rsid    name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi 
rs1     SNP1  A  T 0.05   1       5  56 7    8    9    11  12
rs2     SNP2  T  A 0.05   1       6  55 7    8    9    11  12

虽然我很难理解代码的确切作用。

那么我的代码如何才能准确工作?我真的不明白怎么说 $0 (整行)等​​于 NF 和说 FS$0 (不确定这意味着什么)最后一个字段现在是第一个。我确实意识到 $14="" 没有写,你最终得到 2 个 rsid 列,一个在开头,一个在结尾。

我对使用 awk 还很陌生,所以如果有更简单的方法来实现这一点,我会很乐意去做。

谢谢

请仔细阅读以下内容,如果这对您有帮助,请告诉我。

awk '{
[=10=]=$NF FS[=10=];   ##Re-creating current line by mentioning $NF(last field value), FS(field separator, whose default value is space) then current line value.
=""         ##Now in current line(which is edited above by having last field value to very first) nullifying the last(14th field) here, you could use $NF here too(in case your Input_file have only 14 fields.
}
1              ##1 means we are making condition TRUE here and not mentioning any action so by default print action will happen.
' file.txt     ##Mentioning Input_file name here.

sed

可能更容易
sed -E 's/(.*)\s(\S+)$/ /' file

匹配最后一个字段和该行的其余部分,倒序打印。

\s 是 shorthand 空白字符,相当于 [ \t\r\n\f]\S\s 的否定,用于非空白。 POSIX 等价于 \s[:space:]。如果您的 sed 不支持 shorthand 表示法或者您想要完全的可移植性,您可能需要使用一种等效形式。