Board logo

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

作者: 海鸥    时间: 2023-11-11 11:38     标题: 批处理如何把含有某个字符的行全部替换为固定字符?

求助: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
作者: 77七    时间: 2023-11-11 13:30

  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
复制代码

作者: 海鸥    时间: 2023-11-11 13:36

回复 2# 77七


    感谢大神,百度了一上午
作者: ShowCode    时间: 2023-11-11 19:36

回复 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%"
复制代码

作者: ShowCode    时间: 2023-11-11 19:38

回复 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%"
复制代码

作者: hfxiang    时间: 2023-11-12 14:37

回复 1# 海鸥

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

作者: aloha20200628    时间: 2023-11-12 15:30


针对一楼示例》
  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
复制代码

作者: pd1    时间: 2023-11-12 18:01

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

作者: terse    时间: 2023-11-13 00:54

  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
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2