我有一个格式化的进程列表(顶部输出),我想删除不必要的信息.如何删除例如每行的第二个单词+空格.
例:
1 a hello
2 b hi
3 c ahoi
Run Code Online (Sandbox Code Playgroud)
我想删除ab和c.
P.P*_*.P. 10
你可以使用cut命令.
cut -d' ' -f2 --complement file
Run Code Online (Sandbox Code Playgroud)
--complement做反过来.即-f2选择第二场.而随着--complement如果打印除了第二的所有字段.当您具有可变数量的字段时,这非常有用.
GNU的剪切可以选择--complement.如果--complement不可用,则以下内容相同:
cut -d'' - f1,3-文件
含义:打印第一个字段,然后从第3个字段打印到结尾,即排除第二个字段并打印其余字段. 编辑:
如果您愿意awk,可以:awk {$2=""; print $0}' file
这将第二个设置为空并打印整行(逐个).
使用sed替代第二列:
sed -r 's/(\w+\s+)\w+\s+(.*)/\1\2/' file
1 hello
2 hi
3 ahoi
Run Code Online (Sandbox Code Playgroud)
说明:
(\w+\s+) # Capture the first word and trailing whitespace
\w+\s+ # Match the second word and trailing whitespace
(.*) # Capture everything else on the line
\1\2 # Replace with the captured groups
Run Code Online (Sandbox Code Playgroud)
注意:使用-i选项将结果保存回file,-r对于扩展正则表达式,根据实现检查man可能的结果-E.
或者用于awk仅打印指定的列:
$ awk '{print $1, $3}' file
1 hello
2 hi
3 ahoi
Run Code Online (Sandbox Code Playgroud)
这两种解决方案都有优点,awk解决方案适用于少量固定数量的列,但您需要使用临时文件来存储更改awk '{print $1, $3}' file > tmp; mv tmp file,因为sed解决方案更灵活,因为列不是问题,并且-i选项可以进行编辑地点.