有一个Linux脚本正在占用docker卷并显示卷匹配字符串。
docker volume ls | grep -i $volname | awk '{print $2}'
我需要将此脚本转换为在 Windows 环境中工作。所以PowerShell是我的选择。 Select-String
或多或少像grep
docker volume ls | Select-String $volname
但在PowerShell中没有等同于awk
。所以我尝试使用空格进行拆分:
$volList = docker volume ls |
Select-String "winvolume" |
foreach { $_ -split " " }
但它在数组中有许多空元素(13 个空元素(。我需要删除所有空元素,并且只有带有文本的元素。如何在PowerShell中实现这一点?
Select-String
生成MatchInfo
对象,您需要先从中扩展相关信息。请改用 PowerShell 运算符。
((docker volume ls) -match $volname -split ' +')[1]
在表达式' +'
处拆分会将连续空格视为单个分隔符,就像awk
一样。
一种选择是以稍微不同的方式使用 -split
运算符。 例如,对于此字符串:
"this string has lots of spaces in it "
您只能通过这样做获得"单词":
-split "this string has lots of spaces in it "
这给了:
this
string
has
lots
of
spaces
in
it
因此,在您的情况下,您的代码将是:
$volList = docker volume ls |
Select-String "winvolume" |
foreach { -split $_ }
另一种方法是使用 ConvertFrom-String
。
docker volume ls | Select-String winvolume | ConvertFrom-String | ForEach-Object P2
它有一个别名:
docker volume ls | sls winvolume | cfs | % P2
请注意,如果文本包含小数,它们将被四舍五入。所以最好不要在脚本中使用