
标题: [文本处理] 求助批处理在包含关键词后面添加字符串 [打印本页]
作者: wh123wh123 时间: 2021-5-18 17:23 标题: 求助批处理在包含关键词后面添加字符串
文本A内容如下格式,
[MARK]
00002070=9
01110800=0
00127034=0
00127033=0
00123095=0
[TIPWORD]
01600739=
01600433=
00002801=
00300518=
00002802=
01732016=
文本B内容如下:
002802
600739
732016
请问,如何在文本B里逐一读取每行内容为关键词,并且在文本A里[TIPWORD]字符串下面搜索,如果文本A里出现则在其后面自动添加固定的字符串例如“同V”
最终文本A效果如下:
[MARK]
00002070=9
01110800=0
00127034=0
00127033=0
00123095=0
[TIPWORD]
01600739=同V
01600433=
00002801=
00300518=
00002802=同V
01732016=同V
作者: Gin_Q 时间: 2021-5-18 17:56
本帖最后由 Gin_Q 于 2021-5-18 18:41 编辑
python- # -*- coding:gbk -*-
-
- a_content = []
- b_content = []
-
- a_file = "a.txt"
- b_file = "b.txt"
-
- content_add = "同V"
-
-
- with open(a_file) as fra:
- a_content = fra.readlines()
-
- with open(b_file) as frb:
- b_content = frb.readlines()
-
- for b_line in b_content:
- if b_line[-1] == "\n":
- b_line = b_line[0:-1]
- for index in range(len(a_content)):
- if a_content[index].find(b_line) != -1:
- if a_content[index][-1] == "\n":
- a_content[index] = a_content[index][0:-1] + content_add + "\n"
- else:
- a_content[index] = a_content[index][0:-1] + content_add
-
-
- # 覆盖写入
- with open(a_file, "w") as fw:
- fw.writelines(a_content)
复制代码
作者: wh123wh123 时间: 2021-5-18 18:38
本帖最后由 wh123wh123 于 2021-5-18 19:21 编辑
回复 2# Gin_Q
无效果,文本内容多,按照从A文本里内容“[TIPWORD]”以下开始搜索并添加,到下一个“[”符号为止。因为[×××]这样的标签有多个。
逐一读取B文本里面的行内容。到A文本里面搜索,如果存在则在其后面添加字符串
作者: newswan 时间: 2021-5-19 00:13
本帖最后由 newswan 于 2021-5-19 00:15 编辑
- @echo off
- setlocal enableDelayedExpansion
-
- set path=%gnupath%;%path%
- for /f "delims=" %%b in (b.txt) do (
- sed.exe ' /%%b/s/$/xxx/ ' -i a.txt
- )
复制代码
如果第一段没有匹配的,这个就可以
作者: wh123wh123 时间: 2021-5-19 11:33
回复 4# newswan
无效果
作者: newswan 时间: 2021-5-19 12:49
- for /f "delims=" %%b in (b.txt) do (
- sed.exe -r -e ' /\[TIPWORD\]/,/\[/ {/%%b/s/$/xxx/} ' -i a.txt
- )
复制代码
作者: wh123wh123 时间: 2021-5-19 15:08
回复 6# newswan
你没仔细看我的问题
作者: xczxczxcz 时间: 2021-5-19 16:28
win7 以下 pass- $a = 'xxxxx\a.txt';
- $b = 'xxxxx\b.txt';
- $t = '\xcd\xac\x56'
- [regex]::Replace(((gc $a -read 0) -join "`n"), "(?is)\[TIPWORD[^\[]+",
- {
- $str = $args.Value;
- (gc $b -read 0) | % {
- $str = [regex]::Replace($str, "(?s)(?<=\d+)($_=.*?)(\n?)", "$_=$t`$2");
- }
- $str;
- }
- ) | sc $a -Force;
复制代码
作者: newswan 时间: 2021-5-19 22:31
回复 7# wh123wh123
把 xxx 改成你需要的字符串就行了啊
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |