我有一个像这样的csv文件
name,sex,age
venu,m,16
test,,22
[编辑]
名字也可以有逗号
"venu,gopal",m,16
我想处理性别是什么,并将其保存到另一个文件。
我有一个像这样的剧本
@Echo Off
For /F "usebackq tokens=1-3 delims=," %%a in (test.csv) Do (
echo %%a, %%b, %%c >> test-new.csv
)
但是对于第三条记录,我得到%% b为22应该是空格。如何解决这个问题?
[EDIT2]
我已根据该链接尝试过。我不确定我做错了什么。我遇到了同样的问题。请检查一次。
@echo off
setlocal DisableDelayedExpansion
For /F "usebackq tokens=1-3 delims=" %%x in (C:\somefile.csv) Do (
setlocal EnableDelayedExpansion
set "var=%%x"
set "var=!var:"=""!"
set "var=!var:^=^^!"
set "var=!var:&=^&!"
set "var=!var:|=^|!"
set "var=!var:<=^<!"
set "var=!var:>=^>!"
set "var=!var:,=^,^,!"
set var=!var:""="!
set "var=!var:"=""Q!"
set "var=!var:,,="S"S!"
set "var=!var:^,^,=,!"
set "var=!var:""="!"
set "var=!var:"Q=!"
For /F "tokens=1-3 delims=," %%a in ("!var:"S"S=","!") Do (
endlocal
echo %%~a, %%~b, %%~c
setlocal EnableDelayedExpansion
pause
)
endlocal
)
答案 0 :(得分:2)
这有点棘手,因为多个delim会被压缩为单个delim。
因此,您需要先将它们替换为唯一分隔序列。
@Echo Off
setlocal DisableDelayedExpansion
For /F "usebackq tokens=1-3 delims=" %%a in (test.csv) Do (
set "line=%%a"
setlocal EnableDelayedExpansion
set "line="!line:,=","!""
For /F "tokens=1-3 delims=," %%a in ("!line!") Do (
echo %%~a, %%~b, %%~c
)
)
这会将每列包含在引号中,并且%%~a
引号将在稍后删除
编辑:嵌入式逗号的解决方案
在这种情况下,它只与how to split on ';' in CMD shell
的解决方案略有不同@echo off
setlocal DisableDelayedExpansion
For /F "usebackq tokens=1-3 delims=" %%x in (test.csv) Do (
set "var=%%x"
setlocal EnableDelayedExpansion
set "var=!var:^=^^!"
set "var=!var:&=^&!"
set "var=!var:|=^|!"
set "var=!var:<=^<!"
set "var=!var:>=^>!"
set "var=!var:,=^,^,!"
rem ** This is the key line, the missing quote is intention
call set var=%%var:""="%%
set "var=!var:"="Q!"
set "var=!var:^,^,="C!"
set "var=!var:,,=,!"
set "var=!var:""="!"
set "var="!var:,=","!""
for /F "tokens=1-3 delims=," %%a in ("!var!") do (
endlocal
set "col1=%%~a"
set "col2=%%~b"
set "col3=%%~c"
setlocal EnableDelayedExpansion
if defined col1 (
set "col1=!col1:"C=,!"
set "col1=!col1:"Q="!"
)
if defined col2 (
set "col2=!col2:"C=,!"
set "col2=!col2:"Q="!"
)
if defined col3 (
set "col3=!col3:"C=,!"
set "col3=!col3:"Q="!"
)
echo a=!col1!, b=!col2!, c=!col3!
endlocal
)
)
答案 1 :(得分:0)
使用像SSED这样的字符串编辑器,我已经通过创建一个临时文件来解决这个问题,其中我用“, - ”两次替换“,,”,然后将“ - ”视为一个空字段。原始文件......
ssed "s/,,/,-,/ig;s/,,/,-,/ig" file1.csv > file1.tmp
然后正确分配令牌。如果您需要编辑临时文件然后返回CSV,请使用...
ssed "s/,-,/,,/ig;s/,-,/,,/ig" file1.tmp > file1.csv
这似乎比使用令牌和子程序/等进行飞行字符串替换要简单得多。