Sed insert a line before match, you can use the sed function: i, add a new line before the matched string.
syntax
➜ sed '/option/i newLine' file #option: matched content
➜ sed 'ni newLine' file #n: line number
➜ sed '$i newLine' file #$: last line
examples
Adding new lines before matching content is similar to adding new lines after matching content, using the sed function: i.
In the following example, we will use the sed i function to add a new line before the matched content.
Add a new line before the line containing the string “hello“:
➜ ~ sed '/hello/ised add a new line' test.log
![sed insert line before match](https://www.linuxcommands.site/wp-content/uploads/2020/07/image-13-1024x311.png)
Insert a new line before the first line:
➜ ~ sed '1ised add a new line' test.log
![](https://www.linuxcommands.site/wp-content/uploads/2020/07/image-14-1024x302.png)
Insert a new line before the last line:
➜ ~ sed '$ised add a new line' test.log
this is a test file.
hello
apple
watch
sed add a new line
world
Insert a new line before each line:
➜ ~ sed '/$/i sed add a new line' test.log