用于转换一列 CSV 文件的 PowerShell 脚本

发布于 2024-10-28 10:20:49 字数 208 浏览 1 评论 0原文

我正在寻找一个脚本,不一定要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

玩心态 2024-11-04 10:20:49

使用可以使用正则表达式在开头和结尾插入字符。

get-content ./myonlinecolumn.txt | foreach {$_ -replace "^","'" -replace "`$","',"} 

或者您可以使用格式运算符 -f:

get-content ./myonlinecolumn.txt  | foreach {"'{0}'," -f $_ }

删除最后一个尾随逗号需要更多工作,但这也是可能的

$a = get-content ./myonlinecolumn.txt
get-content ./myonlinecolumn.txt | foreach { if ($_.readcount -lt $a.count) {"'{0}'," -f $_ } else {"'{0}'" -f $_ }}

Use can use a regular expression to insert characters at beginning and end.

get-content ./myonlinecolumn.txt | foreach {$_ -replace "^","'" -replace "`$","',"} 

Or you could use the format operator -f:

get-content ./myonlinecolumn.txt  | foreach {"'{0}'," -f $_ }

Its a bit more work to remove the last trailing comma, but this also possible

$a = get-content ./myonlinecolumn.txt
get-content ./myonlinecolumn.txt | foreach { if ($_.readcount -lt $a.count) {"'{0}'," -f $_ } else {"'{0}'" -f $_ }}
伴我老 2024-11-04 10:20:49

我的第一个想法与乍得已经写过的类似,即检查行号。所以我尝试了不同的解决方案。不太好,但我也发布了:)

((gc c:\before.txt | % {"'"+$_+"'"} ) -join ",*").split("*") | out-file c:\after.txt

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 :)

((gc c:\before.txt | % {"'"+$_+"'"} ) -join ",*").split("*") | out-file c:\after.txt
冰火雁神 2024-11-04 10:20:49

如果您喜欢转义,您可以只使用

(gc myfile | %{"'$_'"}) -join ',
'

or:

(gc myfile | %{"'$_'"}) -join ",`n"

这会将文件加载到字符串数组中 (Get-Content),然后通过将每个字符串放入单引号中来处理它。 (如果您还需要修剪空白,请使用“”'$($_.Trim())'”)。然后用逗号和换行符将行连接起来(这些可以直接嵌入到字符串中)。

如果您的值可以包含单引号(需要转义),那么将其粘贴在那里也很简单:

(gc myfile | %{"'$($_.Trim() -replace "'","''")'"}) -join ",`n"

You can just use

(gc myfile | %{"'$_'"}) -join ',
'

or, if you love escapes:

(gc myfile | %{"'$_'"}) -join ",`n"

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:

(gc myfile | %{"'$($_.Trim() -replace "'","''")'"}) -join ",`n"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文