在 DOS 中打开 csv 文件
是否可以打开一个 csv 文件,例如:
a,b,c,d,e,f,g,h
并让 DOS 读取它(在批处理文件中),检查数据,然后在特定条件下将其从文件中删除?
伪代码:
open csv file
for each letter
if letter is e
remove e from csv file
close and save csv file
编辑:
如果我将数据源从 csv 更改为:
a
b
c
d
e
f
g
h
那么我可以这样称呼:
rename file.txt file.bak
for /f %%a in (file.bak) do (
set hmm=%%a
if !hmm!==e set hmm=helloworld
echo !hmm! >> file.txt)
虽然这会在新更改后打印出原始数据,如下所示:
a
b
c
d
helloworld
f
g
h
a
b
c
d
e
f
g
h
Is it possible to open a csv file such as:
a,b,c,d,e,f,g,h
And have DOS read it in (in a batch file), check the data and then remove it from the file under a certain condition?
Pseudo code:
open csv file
for each letter
if letter is e
remove e from csv file
close and save csv file
EDIT:
If I change my data source from a csv to this:
a
b
c
d
e
f
g
h
Then I can call this:
rename file.txt file.bak
for /f %%a in (file.bak) do (
set hmm=%%a
if !hmm!==e set hmm=helloworld
echo !hmm! >> file.txt)
Although this will print out the original data after the new changes like so:
a
b
c
d
helloworld
f
g
h
a
b
c
d
e
f
g
h
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
FOR /F
,您可以浏览文本文件并处理每列的内容(称为标记),您可以在其中选择分隔列的字符。为了从文件中删除它,我想您必须重新创建一个新文件,在其中决定要写什么和不写什么。
With
FOR /F
, you can go through a text file and process the content of each column (called tokens), where you can choose what character is separating the columns.In order to remove it from the file, I guess you'd have to recreate a new file where you decide what to write and what to not write.
您可以使用 for /f 迭代令牌并使用
设置 str=%str:e=%
删除不需要的标记,然后使用“>”将其间接到另一个文件。
You can iterate through the tokens using for /f and use
set str=%str:e=%
to remove the tokens you don't want and then use ">" to indirect it to another file.
这是我的修复方法:
如果您不删除 bak 文件,它会将 txt 和 bak 都打印到新文件中!诡异的!
Here's my fix:
If you don't delete the bak file it will print both the txt and bak into the new file! Weird!
下面是 Windows PowerShell 2 中的一个基本示例:
这适用于基本情况(单行)。多行 CSV 存在问题;也许有人比我更有 PS-fu 能力可以修复它。
我没有用边界条件(空文件、空行、由单个字母组成的行、相邻逗号、所有 e 的行等)对此进行测试。
对于带有列标题的 CSV 文件,PowerShell 提供 Import-Csv cmdlet (以及 Export-Csv)。
Here's a basic example in Windows PowerShell 2:
This will work on the base case (a single line). It has problems with a multi-line CSV; perhaps someone with more PS-fu than I can fix it.
I did not test this with boundary conditions (empty file, blank line, line consisting of a single letter, adjacent commas, line of all e's, etc.).
For CSV files with column headers, PowerShell provides the Import-Csv cmdlet (as well as Export-Csv).