GNU sed 4.2.2匹配指定行后按需追加字符串及问题排查
Hey there! Let's work through your sed requirement and fix the issues you ran into. First, here's the correct command that meets your needs, followed by an explanation of what went wrong with your attempts.
Correct Sed Command
Assuming your target line to match is Line1 and the specified string you want to check (and insert if missing) is MyTargetString, use this command:
sed '/Line1/{N; /\nMyTargetString/!s/\n/\nMyTargetString\n/;}' your_input_file.txt
How This Works:
/Line1/{: Trigger the following block of commands only when we match the line containingLine1N: Read the next line (Line2) into the pattern space, so the pattern space now holdsLine1\nLine2/\nMyTargetString/!: Only run the next substitution if the pattern space does not contain\nMyTargetString(meaning Line2 is not your specified string)s/\n/\nMyTargetString\n/: Replace the newline between Line1 and Line2 with\nMyTargetString\n—this inserts your specified string right after Line1, before Line2}: Close the command block for theLine1match
Analysis of Your Issues
1. Unexpected Output: Line1 String Line2 String Line3
This usually happens when you didn't add a conditional check before inserting the string. For example, if you used a command like:
/Line1/a MyTargetString
This would always insert MyTargetString after Line1, regardless of what Line2 is. If you combined this with an N command incorrectly, you might end up inserting the string twice (once via a and once via substitution), leading to the duplicate String in your output. The fix is adding the conditional check (/\nMyTargetString/!) to only insert when Line2 doesn't match.
2. Syntax Error: sed: -e expression #1, char 0: unmatched {
This error means sed received an incomplete or malformed command block. Common causes include:
- Missing a closing
}to match the opening{ - Shell quoting issues (e.g., using single quotes but forgetting to close them, which truncates the expression before the closing
}) - No space between the matching pattern and the opening
{(GNU sed requires a space or newline here, e.g.,/Line1/{is valid, but/Line1{is not)
For example, a broken command like this would trigger the error:
sed '/Line1/{N; /\nMyTargetString/!s/\n/\nMyTargetString\n/' your_input_file.txt
Notice the missing } at the end—sed can't find the closing bracket for the block, hence the unmatched { error.
内容的提问来源于stack exchange,提问作者Kacper Witek

