Вот пример того, как вставить строку перед строкой в файле:
пример файла test.txt:
hello line 1
hello line 2
hello line 3
script:
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
Внимание!обратите внимание, что sed имеет в качестве начала замену новой строки на отсутствие пробела - это необходимо, в противном случае результирующий файл будет иметь одну пустую строку в начале
Сценарий находит строку, содержащую «hello line 2», затемвставляет новую строку выше - "привет новая строка"
объяснение команд 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.