简体   繁体   English

awk从输出中删除空间

[英]awk Removing space from output

I am using @"df -lH | grep \\"/Volumes/*\\" | awk '{$1=$2=$3=$4=$5=$6=$7=$8\\"\\"; print $0 }'" for getting locally-mounted volumes path. 我正在使用@"df -lH | grep \\"/Volumes/*\\" | awk '{$1=$2=$3=$4=$5=$6=$7=$8\\"\\"; print $0 }'"以获取本地信息安装的卷路径。 but if volume name contain two or more space (Leopard 1). 但如果卷名包含两个或更多空间(豹1)。 its(awk) removing space from output. 其(awk)从输出中删除空间。

Output: 输出:

$df -lH

Filesystem     Size   Used  Avail Capacity  Mounted on
/dev/disk0s3    81G    61G    19G    77%    /
/dev/disk0s2    81G    72G   8.2G    90%    /Volumes/Leopard  1  2     3
/dev/disk0s4   158G    47G   111G    30%    /Volumes/Backup  

$ df -lH | grep "/Volumes/*"
/dev/disk0s2    81G    72G   8.2G    90%    /Volumes/Leopard  1  2     3
/dev/disk0s4   158G    47G   111G    30%    /Volumes/Backup  

$ df -lH | grep "/Volumes/*" | awk '{$1=$2=$3=$4=$5=""; print $0}'
     /Volumes/Leopard 1 2 3
     /Volumes/Backup

can anyone please help me out? 有人可以帮我吗?

By default awk 's output field separator is a single space. 默认情况下, awk的输出字段分隔符为单个空格。 So the output of your awk command is completely expected. 因此, awk命令的输出完全可以预期。 To get the result you want, you'll need to use some sort of regex, so try this instead with GNU awk : 为了获得想要的结果,您将需要使用某种正则表达式,因此请尝试使用GNU awk

df -lH | awk '/Volumes/ { sub(/^(\S+\s+){5}/, ""); print }'

Or if you have GNU sed : 或者,如果您有GNU sed

df -lH | sed -nr '/Volumes/s/^(\S+\s+){5}//p'

Results: 结果:

/Volumes/Leopard  1  2     3
/Volumes/Backup  

EDIT: 编辑:

I see that BSD/OSX awk doesn't support interval expressions unfortunately. 我看到不幸的是BSD/OSX awk 不支持间隔表达式 Therefore the safest way would be to do this with awk : 因此,最安全的方法是使用awk执行此操作:

df -lH | awk '/Volumes/ { sub(/^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +/, ""); print }'

or with sed : 或使用sed

df -lH | sed -n '/Volumes/s/^[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+//p'

This should also be highly portable! 这也应该是高度可移植的! HTH. HTH。

EDIT: 编辑:

For Mac OSX 10.8 with 8 columns, simply extend the regex: 对于具有8列的Mac OSX 10.8,只需扩展正则表达式即可:

df -lH | awk '/Volumes/ { sub(/^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +/, ""); print }'

or with sed : 或使用sed

df -lH | sed -n '/Volumes/s/^[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+[^ ]\+ \+//p'

This is easier using the mount command, which has simpler output than df , and perl , which supports non-greedy matching: 使用mount命令比输出dfperl更简单,该命令比dfperl更简单,后者支持非贪婪匹配:

:; mount | perl -pe 's/.*? on //;s/ \([^\)]*\)$//'
/
/dev
/Volumes/pro Time Machine 2
/Volumes/b
/Volumes/p
/net
/home

Notice that I do have a volume mounted with spaces in the mount point. 请注意,我确实在安装点上安装了带有空格的卷。

df -lH | grep "/Volumes/*" | perl -pe 's/[^\%]*\%//g'

如果要在awk中执行此操作:

df -lH | grep "/Volumes/*"|awk '{gsub(/[^\%]*\%/,"");print}'

检查此命令的输出,可能有助于您解析并获取信息

mount | column -t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM