用于转换一列 CSV 文件的 PowerShell 脚本
我正在寻找一个脚本,不一定要在 PS 中,但必须在 Windows 下运行,它将如下所示的一列文本文件转换
abc
def
ghi
为
'abc',
'def',
'ghi'
我目前正在使用 =concatenate 在 Excel 中进行此更改,但脚本将是更好的。
I'm looking for a script, doesn't have to be in PS but must run under Windows, that converts a one column text file like below
abc
def
ghi
into
'abc',
'def',
'ghi'
I'm currently making this change in Excel using =concatenate, but a script would be better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用可以使用正则表达式在开头和结尾插入字符。
或者您可以使用格式运算符 -f:
删除最后一个尾随逗号需要更多工作,但这也是可能的
Use can use a regular expression to insert characters at beginning and end.
Or you could use the format operator -f:
Its a bit more work to remove the last trailing comma, but this also possible
我的第一个想法与乍得已经写过的类似,即检查行号。所以我尝试了不同的解决方案。不太好,但我也发布了:)
My first idea was similar to what Chad already wrote, that is a check on the line number. So I've tried a different solution. Not very nice but I post it too :)
如果您喜欢转义,您可以只使用
or:
这会将文件加载到字符串数组中 (
Get-Content
),然后通过将每个字符串放入单引号中来处理它。 (如果您还需要修剪空白,请使用“”'$($_.Trim())'”)。然后用逗号和换行符将行连接起来(这些可以直接嵌入到字符串中)。如果您的值可以包含单引号(需要转义),那么将其粘贴在那里也很简单:
You can just use
or, if you love escapes:
This loads the file into an array of strings (
Get-Content
), then processes each string by putting it into single quotes. (Use `"'$($_.Trim())'" if you need to trim whitespace, too). Then the lines are joined with a comma and line break (those can be embedded directly into strings).If your values can contain single quotes (which need to be escaped) it's trivial to stick that in there, too: