簡體   English   中英

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

[英]How to insert a line using sed before a pattern and after a line number?

如何在模式之前和行號之后使用sed在文件中插入一行? 以及如何在 shell 腳本中使用相同的?

這會在帶有模式的每一行之前插入一行:

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

這使用行號范圍改變了這一點:

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

那么現在如何使用這兩者(我不能)在模式之前和行號或其他方法之后使用sed在文件中插入一行?

您可以編寫 sed 腳本文件並使用:

sed -f sed.script file1 ...

或者您可以使用(多個) -e 'command'選項:

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

如果你想在 append 后面有東西,那么:

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

我假設您只想在當前行號大於某個值時才在模式之前插入行(即,如果模式出現在行號之前,則什么也不做)

如果您沒有綁定到sed

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

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

示例文件 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

output文件test.txt.2

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

注意! 請注意,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. 

簡單的? 從第 12 行到最后:

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

在匹配行之前插入一行:

sed '/^line starts with.*/i insert this line before' filename.txt

Output:

insert this line before
line starts with

在匹配行之后插入一行:

sed '/^line starts with.*/a insert this line after' filename.txt

Output:

line starts with
insert this line after

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM