使用 Bash 删除文本文件中的列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9238736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:32:22  来源:igfitidea点击:

Removing columns in text file with Bash?

linuxbashunix

提问by Homeschooldev

I have a to write a script that remove the Idle column from the output of finger.

我必须编写一个脚本,从finger 的输出中删除空闲列。

>finger
Login    Name                 TTY  Idle  Login  Time   Office  Phone
Billy    Billy Howard        *con  6:55  Fri    19:03
Billy    Billy Howard         s00     5  Fri    19:11
Billy    Billy Howard         s00        Sat    00:27

I tried remove the extra spaces with tr and then using cut with a delimiter of a space to remove the column, but since Idle can have no value I sometimes get the wrong value since tr delimited the spaces were the idle time should be... Does anyone know how I can remove the Idle column?

我尝试用 tr 删除多余的空格,然后使用带有空格分隔符的 cut 来删除列,但是由于 Idle 可能没有值,我有时会得到错误的值,因为 tr 分隔了空格,空闲时间应该是...有谁知道如何删除空闲列?

采纳答案by Hai Vu

This solution is not perfect: the column position and width might change. If they are constant, the following command will do the trick by removing text columns 34 to 39 inclusively:

此解决方案并不完美:列位置和宽度可能会发生变化。如果它们是常量,则以下命令将通过删除文本列 34 到 39 来实现这一点:

finger | colrm 34 39

回答by potong

This might work for you:

这可能对你有用:

finger |  sed 's/\(.\{35\}\).....//'

or this:

或这个:

finger |  cut --complement -c36-40 

回答by Taras

If "\t"is used as column delimiter then you can get rid of 4th column using awkand delete doubled "\t"using sed. For example:

如果"\t"用作列分隔符,那么您可以使用awk删除第 4 列并删除加倍"\t"使用sed。例如:

finger | awk -F"\t" -v 'OFS=\t' '{ =""; print ##代码##}' | sed 's/\t\{2,\}/\t/'