输入文件修改需求:从最后一个foo bar到EOF添加//前缀
解决方案:给文件最后一次出现"foo bar"后的内容添加前缀
要实现你描述的需求——找到文件中最后一次出现foo bar的位置,并给从该位置到文件末尾的内容按指定方式添加// 前缀,我有几个实用的方案,分别适合不同的场景:
方案一:用Python脚本(灵活支持自定义分组)
如果你需要像示例那样对后缀内容进行自定义分组(比如把foo bar flower作为一个块,beauty good作为另一个块),Python脚本是最灵活的选择,能轻松实现自定义规则:
with open('input.txt', 'r') as input_file: full_content = input_file.read() # 定位最后一次出现"foo bar"的位置 last_foo_bar_pos = full_content.rfind('foo bar') if last_foo_bar_pos != -1: # 拆分内容为前缀(最后一次"foo bar"之前的部分)和后缀(之后的部分) prefix_content = full_content[:last_foo_bar_pos] suffix_content = full_content[last_foo_bar_pos:] # 按空格拆分后缀为单词列表 suffix_words = suffix_content.split() # 自定义分组规则(完全匹配你的示例需求) grouped_parts = [] current_idx = 0 # 先处理前三个单词:foo bar flower if len(suffix_words) >= 3: grouped_parts.append(' '.join(suffix_words[current_idx:current_idx+3])) current_idx += 3 # 处理接下来的成对形容词组 while current_idx < len(suffix_words): # 如果当前单词是beauty或ugly,就和下一个单词组成一组 if current_idx + 1 < len(suffix_words) and suffix_words[current_idx] in ('beauty', 'ugly'): grouped_parts.append(' '.join(suffix_words[current_idx:current_idx+2])) current_idx += 2 else: # 单个符号或单词单独成组 grouped_parts.append(suffix_words[current_idx]) current_idx += 1 # 给每个分组添加//前缀,然后拼接起来 formatted_suffix = ' //'.join([f'// {part}' for part in grouped_parts]) # 合并前缀和格式化后的后缀 final_content = prefix_content + formatted_suffix else: # 如果文件中没有"foo bar",直接输出原内容 final_content = full_content # 写入结果到输出文件 with open('output.txt', 'w') as output_file: output_file.write(final_content)
使用方法:把上述代码保存为process.py,然后在终端运行python process.py,就能得到你期望的输出。
方案二:用Awk(命令行快速处理,适合简单场景)
如果你不需要自定义分组,只是想给最后一次foo bar后的每个空格分隔的元素单独添加// 前缀,可以用Awk命令快速实现:
BEGIN { RS = "" # 把整个文件当作一个完整的文本块处理 } { # 匹配最后一次"foo bar"到末尾的内容 if (match($0, /.*(foo bar.*)/, match_arr)) { # 获取前缀部分(最后一次"foo bar"之前的内容) prefix = substr($0, 1, length($0) - length(match_arr[1])) # 获取后缀部分并按空格拆分 split(match_arr[1], suffix_words, / /) # 给每个单词添加//前缀 formatted_suffix = "" for (i in suffix_words) { formatted_suffix = formatted_suffix "// " suffix_words[i] " " } # 去掉末尾多余的空格并输出结果 formatted_suffix = substr(formatted_suffix, 1, length(formatted_suffix)-1) print prefix formatted_suffix } else { # 没有找到"foo bar"时直接输出原内容 print $0 } }
使用方法:把代码保存为script.awk,然后运行awk -f script.awk input.txt > output.txt。
方案三:用Sed+Rev组合(纯命令行,适合单行文本)
如果你的文件内容是单行的,也可以用Sed和Rev工具组合实现快速处理(这里实现给最后一次foo bar后的每个元素添加// 前缀):
rev input.txt | sed 's/rab oof/\/\/ foo bar/' | sed 's/ / \/\/ /g' | rev > output.txt
原理是先反转文本,把最后一次出现的foo bar变成反转后的第一次rab oof,处理后再反转回来,实现对最后一次匹配内容的修改。
内容的提问来源于stack exchange,提问作者Aditya
相关产品推荐
相关产品推荐

