使用批处理文件删除列 .CSV 中的单词

问题描述

我在 .CSV 传入文件夹所在的文件夹中有一个批处理文件

传入的 .CSV 文件一个| GPSPosition |

输出数据看起来像 | 21 deg 14' 4.621" S,159 deg 46' 45.358" W |,是的,它是一列中的一个大短语。

我无法确定如何解决该问题,我想编写一个 .bat 文件以从 .csv 文件中列的每一行的值中删除单词“deg”。

当前结果

| GPSPosition |
| 21 deg 14' 4.621" S,159 deg 46' 45.358" W |
| 21 deg 14' 4.621" S,159 deg 47' 45.358" W |
| 21 deg 14' 4.621" S,159 deg 48' 45.358" W |

预期结果

| GPSPosition |
| 21  14' 4.621" S,159  46' 45.358" W |
| 21  14' 4.621" S,159  47' 45.358" W |
| 21  14' 4.621" S,159  48' 45.358" W |

解决方法

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory,destination directory,target directory,rem batch directory,filenames,output filename and temporary filename [if shown] are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q65987390.txt"
SET "outfile=%destdir%\outfile.txt"

SET "indelims=|,"
SET "outdelim=^|"

(
FOR /f "usebackq tokens=1,2delims=%indelims%" %%b IN ("%filename1%") DO (
 SET "col1=%%b"
 SET "col2=%%c"
 IF DEFINED col2 (
  SET "col1=!col1:deg =!"
  SET "col2=!col2:deg =!"
  ECHO %outdelim%!col1:~1!%outdelim%!col2:~1,-1!%outdelim%
 ) ELSE (
 rem - no col2,so header
  ECHO %outdelim%!col1:~1,-1!%outdelim%Column2header string%outdelim%
 )
)
)>"%outfile%"

GOTO :EOF

从提示中查看 set /? 以破译 :m,n 语法。请注意,管道需要在输出时进行转义(带脱字符号),否则 cmd 会将其视为重定向。

,

很简单:取每一行,用“nothing”替换 deg 并输出结果字符串:

@echo off
setlocal enabledelayedexpansion

(for /f "usebackq delims=" %%a in ("input.csv") do (
  set "line=%%a"
  set "line=!line:deg =!"
  REM set "line=!line:,=|!"
  echo !line!
))>output.csv

set 命令中使用引号可避免管道符号出错,延迟扩展使用 echo 命令处理管道。

(需要时,也用管道符号替换逗号。根据您不需要的示例输出。但我为此插入了代码;如果您想使用它,请删除 REM