将字符插入文本文件的每一行

时间:2012-07-19 17:46:33

标签: file text batch-file insert character

使用批处理文件我需要在现有文本文件的每一行中插入字符。将结果写入将用于填充数据库的新文本文件。插入的字符将成为分隔符,以便按正确的顺序排列数据。

样品:
今天存在的文件:

AAAAAAAAA~ZZZ  
AAAAAAAAA~BB~ZZZ  
AAAAAAAAA~BB~CCCC~ZZZ  
AAAAAAAAA~BBB~CC~ZZZ  

期望的结果:

AAAAAAAAA~~~~ZZZ  
AAAAAAAAA~BB~~~ZZZ  
AAAAAAAAA~BB~CCCC~~ZZZ  
AAAAAAAAA~BBB~CC~~ZZZ 

触发分隔符后的外观:

Part Num    Rev    Stat   Type        
AAAAAAAAA                 ZZZ  
AAAAAAAAA   BB            ZZZ  
AAAAAAAAA   BB     CC     ZZZ  
AAAAAAAAA   BBB    CC     ZZZ  

注意:
第一个字段总是9个字符
最后一个字段总是3个字符
我使用波形符作为字段分隔符

1 个答案:

答案 0 :(得分:0)

这应该这样做。
用法:mapper {sourfile} {targetfile}

mapper.cmd

@echo off
setlocal enabledelayedexpansion
if "%~1" == "" (
  echo No source file specified.
  goto :eof
)
if not exist "%~1" (
  echo Source file not found.
  goto :eof
)
if "%~2" == "" (
  echo No target file specified.
  goto :eof
)
if exist "%~2" (
  echo Target file is already exist.
  goto :eof
)
rem>"%~2"
for /f "tokens=1,2,3,4,5 delims=~" %%a in (%~1) do (
  if "%%b" == "" (
    echo %%a~~~~>>"%~2"
  ) else (
    if "%%c" == "" (
      echo %%a~~~~%%b>>"%~2"
    ) else (
      if "%%d" == "" (
        echo %%a~%%b~~~%%c>>"%~2"
      ) else (
        if "%%e" == "" (
          echo %%a~%%b~%%c~~%%d>>"%~2"
        ) else (
          echo %%a~%%b~%%c~%%d~%%e>>"%~2"
        )
      )
    )
  )
)