咨询sed命令中_.*_与&_的具体用法及相关资料
Hey there! Let's break down that sed command you're using step by step—those underscores and & make total sense once you know the rules. Here's a detailed breakdown:
1. The Custom Separator (_ instead of /)
By default, sed uses / as the separator for the s (substitute) command (like s/search/replace/). But you can use almost any non-whitespace, non-backslash character as a separator—you just need to put it right after the s.
In your command:
sed -i -e 's_.*_text-to-be-insterted-on-each-line&_' '/media/root/<filename>'
The s_ tells sed that _ will be the separator for this substitution. This is super handy if your search or replace text contains / (like file paths)—using a different separator avoids syntax errors.
2. The _.*_ Part
Let's split this into pieces:
- First
_: Marks the start of the search pattern (since we chose_as the separator) .*: This is a regular expression where:.matches any single character (except a newline)*tells sed to match the preceding character (.) zero or more times
Together,.*matches the entire contents of a line (from start to end).
- Second
_: Marks the end of the search pattern and the start of the replacement text.
3. The &_ Part
&: In sed's replacement section, this special character represents the entire text that was matched by the search pattern (in your case, the entire line we captured with.*).- Final
_: This is the closing separator for the substitution command (matching the_we used afters).
What the Whole Command Does
Putting it all together:
For every line in /media/root/<filename>, sed replaces the entire line (.*) with:text-to-be-insterted-on-each-line + [the original line content]
Example:
If your file has a line like Hello, this is a test, after running the command it becomes:text-to-be-insterted-on-each-lineHello, this is a test
Why You Might Not Have Found This in Docs
This separator trick is a lesser-known but core feature of sed's substitute command. Most docs stick to the default / separator, so they don't explicitly highlight that you can swap it out for other characters. The & reference is usually buried in the "substitution flags" or "special characters in replacement text" sections of the sed manual.
内容的提问来源于stack exchange,提问作者alex

