Linux下sed查找替换及行首匹配替换的实现方法
Hey there, let's break down each of your questions with practical, ready-to-use examples that you can test right away:
The core syntax for sed's search-and-replace operation is simple and flexible:
sed 's/search_term/replacement/flags' input_file
s/: Marks the start of a substitute commandflags: Optional modifiers to tweak behavior:g: Replace all occurrences in a line (not just the first match)i: Ignore case when searching-i: Edit the file in-place (use with caution—always back up files first!)
Example: Replace every instance of "foo" with "bar" in example.txt:
sed 's/foo/bar/g' example.txt
To save changes directly to the file:
sed -i 's/foo/bar/g' example.txt
To target lines that begin with a specific string, use the ^ regex anchor (matches the start of a line) as a filter. The syntax looks like this:
sed '/^target_prefix/s/search/replace/flags' input_file
Example: Replace "ERROR" with "WARNING" only on lines that start with "LogEntry:":
sed '/^LogEntry:/s/ERROR/WARNING/g' system_logs.txt
If you want to replace the entire line that matches the prefix, use the c\ command:
sed '/^Deprecated:/c\// This line has been marked as deprecated' code_file.py
Using sed (best for large files or one-liners)
Sed’s & character represents the entire matched string, making this task trivial. Just prepend three spaces to the match:
sed 's/abc\.xyz/ &/' input_file
Note the backslash before the dot (\.)—dots are special regex characters, so we escape it to match a literal dot. Add the g flag to replace every occurrence in a line:
sed 's/abc\.xyz/ &/g' input_file
Using Bash (for small files or inline processing)
If you prefer a pure bash approach, use parameter expansion in a loop to modify each line:
while IFS= read -r line; do echo "${line//abc.xyz/ abc.xyz}" done < input.txt > output.txt
This reads each line, replaces all instances of "abc.xyz" with the string prefixed by three spaces, and writes the result to output.txt.
内容的提问来源于stack exchange,提问作者preethy tulpi




