[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[文本处理] 批处理如何把含有某个字符的行全部替换为固定字符?

求助:TXT文本
110,3.2212,1,33,面,I49G008023,,,@
J1,1,3953971.8078,37357714.5646
111,3.2212,1,33,面,I49G008023,,,@
J3,1,3954005.9406,37357705.3199
112,3.2212,1,33,面,I49G008023,,,@
J5,1,3954002.7896,37357691.3276
我想把含有@字符行全部换成这个字符串 *,,3000-0   如下结果,怎么办
*,,3000-0
J1,1,3953971.8078,37357714.5646
*,,3000-0
J3,1,3954005.9406,37357705.3199
*,,3000-0
J5,1,3954002.7896,37357691.3276

  1. @echo off
  2. set "file=a.txt"
  3. set "str=*,,3000-0"
  4. (for /f "usebackq delims=" %%a in ("%file%") do (
  5.      set "line=%%a"
  6.       setlocal enabledelayedexpansion
  7.       if "!line!" == "!line:@=!" (echo,!line!) else (echo,!str!)
  8.       endlocal
  9. ))>b.txt
  10. pause
复制代码

TOP

最近在学sed和gawk,凑个热闹
  1. sed -r "s/.*@.*/*,,3000-0/" 1.txt>2.txt
复制代码

TOP


针对一楼示例》
  1. @echo off &setlocal enabledelayedexpansion
  2. (for /f "delims=" %%s in (a.txt) do (
  3. set "s=%%s" & if "!s:~-1!"=="@" (echo,*,,3000-0) else (echo,%%s)
  4. ))>b.txt
  5. endlocal &exit/b
复制代码

TOP

回复 1# 海鸥

第3方工具sed( http://bcn.bathome.net/tool/4.9/sed.exe )实现方法如下:
  1. sed "/@/c*,,3000-0" a.txt>b.txt
复制代码

TOP

回复 1# 海鸥


V2.bat
  1. @echo off
  2. set "FileOld=1.txt"
  3. set "FileNew=2.txt"
  4. cd /d "%~dp0"
  5. (for /f "tokens=1* delims=:" %%a in ('findstr /n .* "%FileOld%"') do (
  6.     set "StrOld=%%b"
  7.     setlocal enabledelayedexpansion
  8.     set "StrNew=!StrOld:@=!"
  9.     if "!StrOld!" == "" (
  10.         echo,
  11.     ) else if not "!StrNew!" == "!StrOld!" (
  12.         echo,*,,3000-0
  13.     ) else (
  14.         echo,!StrOld!
  15.     )
  16.     endlocal
  17. ))>"%FileNew%"
复制代码
测试代码之前请做好备份

TOP

回复 1# 海鸥


V1.bat
  1. @echo off
  2. set "FileOld=1.txt"
  3. set "FileNew=2.txt"
  4. cd /d "%~dp0"
  5. (for /f "delims=" %%i in ('type "%FileOld%"') do (
  6.     set "StrOld=%%i"
  7.     setlocal enabledelayedexpansion
  8.     set "StrNew=!StrOld:@=!"
  9.     if not "!StrNew!" == "!StrOld!" (
  10.         echo,*,,3000-0
  11.     ) else (
  12.         echo,!StrOld!
  13.     )
  14.     endlocal
  15. ))>"%FileNew%"
复制代码
测试代码之前请做好备份

TOP

回复 2# 77七


    感谢大神,百度了一上午

TOP

  1. @echo off
  2. set input=1.txt
  3. set output=2.txt
  4. for /f "tokens=1* delims=[]" %%a in ('find /n "@" ^<"%input%"') do (
  5. set _%%a=1
  6. )
  7. (for /f "tokens=1* delims=[]" %%a in ('find /n /v "" ^<"%input%"') do (
  8. if defined _%%a (
  9. echo *,,3000-0
  10. ) else (
  11. echo=%%b
  12. )
  13. ))>"%output%"
  14. pause
复制代码
bat小白,请多指教!谢谢!

TOP

返回列表