【问题标题】:Applying some changes in a tab separated text file using AWK使用 AWK 在制表符分隔的文本文件中应用一些更改
【发布时间】:2020-05-19 00:42:36
【问题描述】:

我有一个制表符分隔的文本文件,像这个小例子:

小例子:

#type   cNA NA  me  ion Dir Mism    Bulge
X   GAAGC   GAAGa   chr8    3997355     -   5   0
X   GAAGC   GAAGC   chr8    11720692    +   5   0
X   GAAGC   GAAGC   chr8    23414961    -   5   0

并希望创建一个类似预期输出的新文件,其中删除第一行并按此顺序重新组织列:

1) columns 1 and 8 are removed.
2) 2nd column (small example file) moved to 1st column (expected output).
3) 4th column moved to the 2nd column.
4) 5th column moved to 3rd column.
5) 3rd column moved to 4th column.
6) 6th column moved to 5th column.
7) 7th column moved to 6th column.

这是预期的输出:

预期输出:

GAAGC   chr8    3997355     GAAGa   -   5
GAAGC   chr8    11720692    GAAGC   +   5
GAAGC   chr8    23414961    GAAGC   -   5

我正在尝试使用以下命令在AWK 中执行此操作:

awk -F '\t' '{ print $2 $4 $5 $3 $6 $7}' infile.txt > output.txt

但我得到的结果与预期的输出不同。你知道如何修复代码吗?

【问题讨论】:

    标签: linux shell file text awk


    【解决方案1】:

    我不确定您为什么要重新分配字段?当我们可以像这样简单地打印它们时:

    awk 'FNR==1{next} {print $2,$4,$5,$3,$6,$7}' Input_file
    

    或者添加一个制表符分隔的输出使用:

    awk 'BEGIN{OFS="\t"} FNR==1{next} {print $2,$4,$5,$3,$6,$7}' Input_file
    

    awk 'FNR>1{print $2,$4,$5,$3,$6,$7}' Input_file
    

    awk 'BEGIN{OFS="\t"} FNR>1{print $2,$4,$5,$3,$6,$7}' Input_file
    


    如果 OP 只愿意使用字段重新分配方法,那么可以尝试跟随。

    awk '
    BEGIN{
      OFS="\t"
    }
    FNR==1{
      next
    }
    {
      $1=$2
      $2=$4
      $4=$3
      $3=$5
      $5=$6
      $6=$7
      $7=$8=""
      sub(/ +$/,"")
    }
    1
    '  Input_file
    

    【讨论】:

    • 谢谢。但我想制作制表符分隔文件。
    • 您还需要将 OFS 设置为选项卡
    • @user10657934,现在请检查一次吗?
    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多