Shell无法替换文件字符串:给指定模式行追加内容的问题求助
Hey there! Let's break down why your initial sed attempt didn't work and walk through several reliable, optimized methods to get this task done right—while keeping your line order intact.
为什么sed没反应?
Your matching pattern has a bunch of special regular expression characters (like ., |, and ") that weren't escaped. By default, sed treats these as regex operators instead of literal characters, so it couldn't find the line you wanted to modify—hence no changes and no errors.
修正后的sed方案
Let's fix the sed command by escaping those special characters. If you want to append a specific string (say, _NEW_SUFFIX) to the exact line pattern you mentioned:
# For Linux systems sed -i '/Var2="2018-Feb-22 06:02:01\.1234\|AVC-00123HHGF \|"/s/$/_NEW_SUFFIX/' filename # For macOS systems (note the empty string after -i) sed -i '' '/Var2="2018-Feb-22 06:02:01\.1234\|AVC-00123HHGF \|"/s/$/_NEW_SUFFIX/' filename
If your pattern is dynamic (e.g., the date or AVC code changes but the format stays the same), use a more flexible regex to match any line fitting that structure:
sed -E -i '/Var2="[0-9]{4}-[A-Za-z]{3}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{4}\|AVC-[A-Z0-9]+ \|"/s/$/_NEW_SUFFIX/' filename
The -E flag enables extended regex, making the pattern easier to write and read.
另一种选择:awk
awk is great for this kind of line-by-line processing and can feel more intuitive for some folks. Here's how to do it:
awk '/Var2="2018-Feb-22 06:02:01\.1234\|AVC-00123HHGF \|"/{print $0"_NEW_SUFFIX"; next}1' filename > tempfile && mv tempfile filename
解释:
- The regex matches your target line. When found, it prints the line plus your appended string, then skips to the next line.
- The
1at the end tells awk to print all other lines exactly as they are. - We redirect to a temp file first, then overwrite the original to avoid issues with in-place editing.
优化你的双文件方案
If you prefer sticking with a two-file approach (maybe for transparency), you can streamline it with a single command instead of manual steps:
# Copy non-matching lines to a temp file, then append the modified matching line grep -v 'Var2="2018-Feb-22 06:02:01\.1234\|AVC-00123HHGF \|"' filename > tempfile grep 'Var2="2018-Feb-22 06:02:01\.1234\|AVC-00123HHGF \|"' filename | sed 's/$/_NEW_SUFFIX/' >> tempfile mv tempfile filename
This keeps your original logic but automates it in one go, so you don't have to manually edit two files.
内容的提问来源于stack exchange,提问作者FlorentinaP

