You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询sed命令中_.*_与&_的具体用法及相关资料

Understanding Your Sed Command's "Weird" Syntax

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 after s).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:19:15