How to insert a line into a file using sed
before a pattern and after a line number? And how to use the same in shell script?
This inserts a line before
Simple? From line 12 to the end:
sed '12,$ s/.*Sysadmin.*/Linux Scripting\n&/' filename.txt
You can either write a sed script file and use:
sed -f sed.script file1 ...
Or you can use (multiple) -e 'command'
options:
sed -e '/SysAdmin/i\
Linux Scripting' -e '1,$s/A/a/' file1 ...
If you want to append something after a line, then:
sed -e '234a\
Text to insert after line 234' file1 ...
I assume you want to insert the line before a pattern only if the current line number is greater than some value (i.e. if the pattern occurs before the line number, do nothing)
If you're not tied to sed
:
awk -v lineno=$line -v patt="$pattern" -v text="$line_to_insert" '
NR > lineno && $0 ~ patt {print text}
{print}
' input > output
here is an example of how to insert a line before a line in a file:
example file 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
output file test.txt.2
hello line 1
hello new line
hello line 2
hello line 3
NB! notice that the sed has as beginning a substitution of a newline to no space - this is necessary otherwise resulting file will have one empty line in the beginning
The script finds the line containing "hello line 2", it then inserts a new line above -- "hello new line"
explanation of sed commands:
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.