在PowerShell中相当于*nix fold

yzo*_*org 2 powershell powershell-4.0

今天我有几百个项目(来自SQL查询的ID),需要将它们粘贴到另一个查询中,以供分析师阅读.我需要*nix fold命令.我想拍摄300行并将它们重新格式化为每行由空格分隔的多个数字.我会用的fold -w 100 -s.

*nix上的类似工具包括fmtpar.

在Windows上有一种简单的方法在PowerShell中执行此操作吗?我期望其中一个*-Format命令行程序可以做到,但我找不到它.我正在使用PowerShell v4.

请参阅https://unix.stackexchange.com/questions/25173/how-can-i-wrap-text-at-a-certain-column-size

# Input Data
# simulate a set of 300 numeric IDs from 100,000 to 150,000
100001..100330 | 
    Out-File _sql.txt -Encoding ascii

# I want output like:
# 100001,  100002,  100003,  100004,  100005, ... 100010, 100011
# 100012,  100013,  100014,  100015,  100016, ... 100021, 100021
# each line less than 100 characters.
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 7

根据文件的大小,您可以将其全部读入内存,将其与空格连接,然后拆分为100*个字符或下一个空格

(Get-Content C:\Temp\test.txt) -join " " -split '(.{100,}?[ |$])' | Where-Object{$_}
Run Code Online (Sandbox Code Playgroud)

那个正则表达式会查找100个字符,然后是第一个空格.然后匹配,-split但由于模式包含在括号中,因此返回匹配而不是丢弃.该Where删除在比赛之间产生的空项.

小样本证明理论

@"
134
124
1
225
234
4
34
2
42
342
5
5
2
6
"@.split("`n") -join " "  -split '(.{10,}?[ |$])' | Where-Object{$_}
Run Code Online (Sandbox Code Playgroud)

以上分为10个字符.如果不能仍然保留数字.样本是基于我用我的头撞在键盘上.

134 124 1 
225 234 4 
34 2 42 
342 5 5 
2 6
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其转换为功能,以便获得您最有可能寻找的简单性.它可以变得更好,但这不是答案的焦点.

Function Get-Folded{
    Param(
        [string[]]$Strings,
        [int]$Wrap = 50
    )
    $strings  -join " " -split "(.{$wrap,}?[ |$])" | Where-Object{$_}
}
Run Code Online (Sandbox Code Playgroud)

再次与样品

PS C:\Users\mcameron> Get-Folded -Strings (Get-Content C:\temp\test.txt) -wrap 40
"Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, sed do eiusmod tempor incididunt 
ut labore et dolore magna aliqua. Ut enim 
ad minim veniam, quis nostrud exercitation 
... output truncated...
Run Code Online (Sandbox Code Playgroud)

您可以看到它应该拆分为40个字符,但第二行更长.它在40之后分裂到下一个空格以保留这个词.