【问题标题】:bash awk first 1st column and 3rd column with everything afterbash awk 第一列和第三列之后的所有内容
【发布时间】:2013-01-26 00:47:59
【问题描述】:

我正在编写以下 bash 脚本:

# contents of dbfake file
1 100% file 1
2 99%  file name 2
3 100% file name 3

#!/bin/bash

# cat out data
cat dbfake |

# select lines containing 100%
grep 100% |

# print the first and third columns
awk '{print $1, $3}' |

# echo out id and file name and log
xargs -rI % sh -c '{ echo %; echo "%" >> "fake.log"; }'

exit 0

这个脚本可以正常工作,但我如何打印第 3 列中的所有内容,然后打印之后的所有列?

【问题讨论】:

    标签: bash awk xargs


    【解决方案1】:

    在这种情况下,您可以使用 cut 代替 awk:

      cut -f1,3- -d ' '
    

    【讨论】:

      【解决方案2】:
      awk '{ $2 = ""; print }' # remove col 2
      

      【讨论】:

        【解决方案3】:

        如果你不介意一点空格:

        awk '{ $2="" }1'
        

        但是UUOCgrep

        < dbfake awk '/100%/ { $2="" }1' | ...
        

        如果您想修剪该空白:

        < dbfake awk '/100%/ { $2=""; sub(FS "+", FS) }1' | ...
        


        为了好玩,这是使用GNU sed的另一种方式:

        < dbfake sed -r '/100%/s/^(\S+)\s+\S+(.*)/\1\2/' | ...
        

        【讨论】:

          【解决方案4】:

          你只需要:

          awk 'sub(/.*100% /,"")' dbfake | tee "fake.log"
          

          【讨论】:

            【解决方案5】:

            其他人以各种方式回应,但我想指出,使用 xargs 来复用输出是相当糟糕的主意。

            相反,你为什么不呢:

            awk '$2=="100%" { sub("100%[[:space:]]*",""); print; print >>"fake.log"}' dbfake
            

            就是这样。你不需要 grep,你不需要多个管道,当然你也不需要为你输出的每一行 fork shell。

            你可以做awk ...; print}' | tee fake.log,但是如果 awk 也能处理的话,分叉 tee 没有多大意义。

            【讨论】:

              猜你喜欢
              • 2020-10-31
              • 2015-11-04
              • 1970-01-01
              • 2017-07-22
              • 2020-12-11
              • 1970-01-01
              • 2012-12-03
              • 1970-01-01
              • 2022-12-04
              相关资源
              最近更新 更多