简体   繁体   English

如果第一行与模式匹配,则 sed 在文件的第一行插入字符串

[英]Sed insert string at first line of file if the first line matches pattern

I have an sed question to which I couldn't find the answer anywhere yet:我有一个sed问题,我在任何地方都找不到答案:

I have a bunch of files, some of them start with the string ### and some don't.我有一堆文件,其中一些以字符串###开头,有些则不是。 In every file which starts with ### I would like to insert some multi-line string before the current first line.在每个以###开头的文件中,我想在当前第一行之前插入一些多行字符串。

fe If a file looks like fe 如果文件看起来像

### the first line

abc cba jfkdslfjslkd

I want the multi line string to get inserted at the top我希望多行字符串插入顶部

my
multi
line
string

### the first line

abc cba jfkdslfjslkd

Nothing else in the file should get modified.文件中的任何其他内容都不应被修改。

If a file does not start with ### then I don't want to edit it.如果文件不以###开头,那么我不想编辑它。

Using sed使用 sed

First let's define your string:首先让我们定义你的字符串:

$ s='my\nmulti\nline\nstring\n\n'

Now, let's run a sed command:现在,让我们运行一个 sed 命令:

$ sed "1s/^###/$s&/" File
my
multi
line
string

### the first line

abc cba jfkdslfjslkd

How it works:这个怎么运作:

  • 1s/old/new/ substitutes new for old but only if old occurs on the first line. 1s/old/new/new代替old前提old出现在第一行。

  • 1s/^###/$s&/ substitutes the string $s in front of ### if the first line starts with ### .如果第一行以###开头,则1s/^###/$s&/替换###前面的字符串$s

Warning: The string s should not contain any sed-active characters.警告:字符串s不应包含任何 sed-active 字符。 If the string s is not under your control, this is a security violation.如果字符串s不在您的控制之下,则这是安全违规。

Using awk使用 awk

Awk has sensible handling of variables and this avoids the security problem. awk 对变量进行了合理的处理,这避免了安全问题。

$ s='my\nmulti\nline\nstring\n'
$ awk -v string="$s" 'NR==1 && /^###/ {print string} 1' File
my
multi
line
string

### the first line

abc cba jfkdslfjslkd

This may be a simpler solution in sed:这可能是 sed 中更简单的解决方案:

Input:输入:

▶ string='my\nmulti\nline\nstring\n'
▶ cat FILE 
### the first line

abc cba jfkdslfjslkd

### other lines

Solution:解决方案:

▶ gsed -e '1{/^###/i\' -e "$string" -e '}' FILE
my
multi
line
string

### the first line

abc cba jfkdslfjslkd

### other lines"

Explanation:解释:

  • Use of multiple -e allows us to avoid interpolating strings into the sed command.使用多个-e可以避免将字符串插入到 sed 命令中。
  • The GNU alternative form ofi\\ command as noted in the GNU manual. GNU 手册中提到的i\\命令的 GNU 替代形式。

tried on gnu sed and bash尝试使用 gnu sed 和 bash

$ a='my\nmulti\nline\nstring'; echo -e $a
my
multi
line
string

$  sed -Ee "0,/^###/{/^###/i$a" -e '}' file*

my
multi
line
string
### the first line

abc cba jfkdslfjslkd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM