如何用sed精准替换指定单词并避免双引号误匹配?
Got it, let's sort out this sed issue you're facing. The problem where CBVGHIER_TSV_WB798 gets mangled into CB"VGHIER_TSV_WB798" means your current sed expression isn't matching the entire target word correctly—instead, it's targeting a substring and adding quotes mid-word.
The Correct Sed Approach
We need a regex that:
- Matches the full target word, regardless of whether it already has surrounding double quotes
- Strips any existing quotes from the word
- Re-wraps the entire word in fresh double quotes
Here's the command for your specific target word:
sed -E 's/["]?CBVGHIER_TSV_WB798["]?/"CBVGHIER_TSV_WB798"/g' your_input_file.txt
Let's break down what this does:
-Eenables extended regular expressions (makes the syntax cleaner)["]?matches 0 or 1 double quote (handles cases where the word is already quoted or not)- We explicitly match the full target word (
CBVGHIER_TSV_WB798) to avoid partial matches - The replacement wraps the entire word in double quotes, ensuring no mid-word quoting
Handling Multiple Target Words
Since you mentioned you have a separate sed statement for a second word, you can combine both into one command using alternation (|) to avoid running sed twice:
sed -E 's/["]?(CBVGHIER_TSV_WB798|YOUR_SECOND_TARGET_WORD)["]?/"\1"/g' your_input_file.txt
(word1|word2)creates a group matching either target word\1references the matched word from the group, so we don't have to repeat the word in the replacement
Why Your Previous Command Failed
Chances are your original regex was targeting a substring (like CB) instead of the full word, or didn't account for existing quotes properly. By explicitly matching the entire target word and handling optional surrounding quotes, we eliminate those partial-match errors.
Test this command with your file—you'll get clean, correctly quoted target words every time.
内容的提问来源于stack exchange,提问作者ram

