如何用正则在x、y中搜索a并按需替换y,及筛选含特定片段的文本行
Question 1: Conditional Replacement in y Only If a Is Found in x
The core idea here is to first verify if your target a exists in x, then only run the replacement on y if that check passes. The implementation depends on the tool or language you’re using—here are two common, practical approaches:
Using Python (Flexible Scripting)
If x and y are separate strings or variables, Python’s re module makes this straightforward:
import re # Define your inputs x = "This is x, containing the target a" y = "This is y, where we'll replace a only if x has it" target = "a" replacement = "REPLACED_A" # Check if target exists in x if re.search(re.escape(target), x): # Perform replacement on y modified_y = re.sub(re.escape(target), replacement, y) else: modified_y = y # Leave y unchanged if x doesn't have the target print(modified_y)
If x and y are sections of the same text (like specific lines in a file), adjust this to track whether you’ve found x with the target before processing the y lines.
Using Awk (Command Line for Text Files)
For files where x and y are lines or blocks, awk can track the condition dynamically:
# Example: Mark a flag if a line contains "target_a", then replace "a" in subsequent lines BEGIN { flag=0 } /target_a/ { flag=1 } flag { gsub(/a/, "REPLACED_A"); print } !flag { print }
Run this with awk -f script.awk input.txt > output.txt
Question 2: Filter Lines Where the First Argument Contains "_arrow"
For your large text file, you want to keep only lines where the first quoted argument in recipes.addShaped() includes "_arrow". Here are efficient ways to do this:
Using Grep (Fast for Large Files)
Grep is ideal for quick line filtering. The regex targets lines where the first quoted string after recipes.addShaped( contains "_arrow":
grep -E '^recipes\.addShaped\("[^"]*_arrow"[,)]' your_file.txt > filtered_file.txt
Breakdown of the regex:
^recipes\.addShaped\(: Matches the start of the line and the function call"[^"]*_arrow": Matches a quoted string that includes "_arrow" (the first argument)[,)]: Ensures we’re looking at the end of the first argument (either a comma or closing parenthesis)
Using Sed (In-Place Editing)
If you want to modify the original file directly (always make a backup first!), use sed to delete all non-matching lines:
sed -i.bak '/^recipes\.addShaped\("[^"]*_arrow"[,)]/!d' your_file.txt
The !d means "delete lines that don’t match the pattern", and -i.bak creates a backup of the original file.
Using Python (For Custom Adjustments)
If you need more control (like adding extra logic later), Python works well too:
import re with open("your_file.txt", "r") as infile, open("filtered.txt", "w") as outfile: for line in infile: # Match the first quoted argument in recipes.addShaped() match = re.match(r'recipes\.addShaped\("([^"]+)"', line.strip()) if match and "_arrow" in match.group(1): outfile.write(line)
内容的提问来源于stack exchange,提问作者Devon Ferree

