【问题标题】:Linux shell command to reverse the field order of varying length text recordsLinux shell命令反转变长文本记录的字段顺序
【发布时间】:2014-03-23 13:54:27
【问题描述】:

我想要一个命令行咒语来反转任意长度文本记录的字段顺序。 Rearrange columns using cutElegant way to reverse column order 中提供的解决方案并不能解决这个问题,因为它们假定字段数量是固定的,尽管它们可能会稍作改动。

有点像tac 命令,它展示了反向cat 功能。我想知道ohce 命令会做什么(如果它存在的话)来反转echo 功能。

例如:

a b c d
e f
g h i

应该转化为

d c b a
f e
i h g

【问题讨论】:

    标签: linux shell parsing reverse command-line-interface


    【解决方案1】:

    使用datamash

    echo 'a b c d
    e f          
    g h i' | datamash --no-strict -t' ' reverse
    

    输出:

    d c b a
    f e
    i h g
    

    rev不同,它不会反转单词:

    echo 'abc xyz' | datamash --no-strict -t' ' reverse
    

    输出:

    xyz abc
    

    【讨论】:

      【解决方案2】:

      有一个命令可以做到这一点,它被命名为 rev 来自 util-linux

      $ rev file
      d c b a
      f e
      i h g
      

      或使用

      $ perl -lane 'print join " ", reverse @F' file
      d c b a
      f e
      i h g
      

      但是就像你在 cmets 中解释的那样,如果你想要最新的 3 个专栏,你可以使用

      awk '{print $(NF-2), $(NF-1), $NF}' file
      

      【讨论】:

      • rev 反转字符,因此像abc def 这样的行将显示为fed cba。这个问题模棱两可,所以@chiam 必须澄清一下。
      • 通过这两种解决方案,OP 可以选择,他们处理这两种情况。
      • 通过为每行添加换行符来修复 perl 版本
      • 对不起,含糊不清,但 rev 反转所有字符这一事实并不影响它对我的用处,只需再次应用它。 echo 给我最后三个字段 | rev | (read a b c 忽略其余部分;echo $a $b $c) | rev
      • 如果您想要最新的 3 列,请查看我的 awk 解决方案。
      【解决方案3】:

      使用 bash:

      while read -ra words; do 
          for ((i=${#words[@]}-1; i>=0; i--)); do 
              printf "%s " "${words[i]}"
          done
          echo
      done < file
      

      【讨论】:

        【解决方案4】:

        使用 awk:

        awk '{for (i=NF; i>1; i--) printf "%s%s", $i, FS; print $i }' file
        d c b a
        f e
        i h g
        

        【讨论】:

          猜你喜欢
          • 2010-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-01
          • 2013-10-23
          • 2015-03-30
          • 1970-01-01
          相关资源
          最近更新 更多