如何在模式之前和行号之后使用sed插入一行?

时间:2011-06-08 20:01:15

标签: shell unix awk sed

如何在模式之前和行号之后使用sed将行插入文件?以及如何在shell脚本中使用相同的东西?

这会在每行前面插入一行代码:

sed '/Sysadmin/i \ Linux Scripting' filename.txt

这会使用行号范围更改此内容:

sed '1,$ s/A/a/'

那么现在如何使用这些(我不能)在模式之前和行号或其他方法之后使用sed将行插入文件中?

4 个答案:

答案 0 :(得分:26)

您可以编写sed脚本文件并使用:

sed -f sed.script file1 ...

或者您可以使用(多个)-e 'command'选项:

sed -e '/SysAdmin/i\
Linux Scripting' -e '1,$s/A/a/' file1 ...

如果你想在一行之后附加一些内容,那么:

sed -e '234a\
Text to insert after line 234' file1 ...

答案 1 :(得分:8)

我假设您只想在当前行号大于某个值时插入模式前的行(即如果模式出现在行号之前,则不执行任何操作)

如果您不依赖于sed

awk -v lineno=$line -v patt="$pattern" -v text="$line_to_insert" '
    NR > lineno && $0 ~ patt {print text}
    {print}
' input > output

答案 2 :(得分:0)

这是一个如何在文件中的一行之前插入一行的示例:

示例文件test.txt:

hello line 1
hello line 2
hello line 3

脚本:

sed -n 'H;${x;s/^\n//;s/hello line 2/hello new line\n&/;p;}' test.txt > test.txt.2

输出文件test.txt.2

hello line 1
hello new line
hello line 2
hello line 3

NB!请注意,sed的开头是换行替换为空格 - 这是必要的,否则生成的文件将在开头有一个空行

脚本找到包含" hello line 2"的行,然后在上面插入一个新行 - " hello new line"

sed命令的解释:

sed -n:
suppress automatic printing of pattern space

H;${x;s/test/next/;p}

/<pattern>/  search for a <pattern>
${}  do this 'block' of code
H    put the pattern match in the hold space
s/   substitute test for next everywhere in the space
x    swap the hold with the pattern space
p    Print the current pattern hold space. 

答案 3 :(得分:0)

简单吗?从第12行到结尾:

sed '12,$ s/.*Sysadmin.*/Linux Scripting\n&/' filename.txt