Today I had a few hundred items (IDs from SQL query) and needed to paste them into another query to be readable by an analyst. I needed *nix fold
command. I wanted to take the 300 lines and reformat them as multiple numbers per line seperated by a space. I would have used fold -w 100 -s
.
Similar tools on *nix include fmt
and par
.
On Windows is there an easy way to do this in PowerShell? I expected one of the *-Format
commandlets to do it, but I couldn't find it. I'm using PowerShell v4.
See 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.
When I saw this, the first thing that came to my mind was abusing Format-Table to do this, mostly because it knows how to break the lines properly when you specify a width. After coming up with a function, it seems that the other solutions presented are shorter and probably easier to understand, but I figured I'd still go ahead and post this solution anyway:
Using it gives output like this:
If it's one item per line, and you want to join every 100 items onto a single line separated by a space you could put all the output into a text file then do this:
Depending on how big the file is you could read it all into memory, join it with spaces and then split on 100* characters or the next space
That regex looks for 100 characters then the first space after that. That match is then
-split
but since the pattern is wrapped in parenthesis the match is returned instead of discarded. TheWhere
removes the empty entries that are created in between the matches.Small sample to prove theory
The above splits on 10 characters where possible. If it cannot the numbers are still preserved. Sample is based on me banging on the keyboard with my head.
You could then make this into a function to get the simplicity back that you are most likely looking for. It can get better but this isn't really the focus of the answer.
Again with the samples
You can see that it was supposed to split on 40 characters but the second line is longer. It split on the next space after 40 to preserve the word.
I came up with this:
Maybe not as compact as you were hoping for, and there may be better ways to do it, but it seems to work.
This is what I ended up using.
Thanks everyone for the effort and the answers. I'm really surprised there wasn't a way to do this with
Format-Table
without the use of[guid]::Empty
in Rohn Edward's answer.My IDs are much more consistent than the example I gave, so Noah's use of
gc -ReadCount
is by far the simplest solution in this particular data set, but in the future I'd probably use Matt's answer or the answers linked to by Emperor in comments.