sed: add or append character at beginning or end of line (row) of a file

You may have some requirement wherein you have to cut a row or get some output from a file and append it to another file as a prefix or suffix.

or you know that you have to add some content as a prefix or suffix in front of every line of a file ot may be at some specific line of a file.

There can be many such similar requirements where you can try the below options

Here is my sample file

# cat /tmp/file
Line One
Line Two
Line Three
Line Four
Line Five

 

Append a prefix in front of every line of a file

Here we will add a text "PREFIX:" in front of every line of my file

# sed -ne 's/.*/PREFIX: &/p' /tmp/file
PREFIX: Line One
PREFIX: Line Two
PREFIX: Line Three
PREFIX: Line Four
PREFIX: Line Five

 

To make the changes within the same file

# sed -i 's/.*/PREFIX: &/' /tmp/file

 

Append a suffix at the end of every line of a file

# sed -ne 's/$/ :SUFFIX &/p' /tmp/file
Line One :SUFFIX
Line Two :SUFFIX
Line Three :SUFFIX
Line Four :SUFFIX
Line Five :SUFFIX

 

To make the changes within the same file

# sed -i 's/$/ :SUFFIX &/' /tmp/file

 

Append a prefix or a suffix at a specific line

This can be done assuming you know the line number where you have to append the new content

For example I want to append this prefix and suffix at line number 2

# sed -e 2's/$/ :SUFFIX &/' /tmp/file
Line One
Line Two :SUFFIX
Line Three
Line Four
Line Five

 

Again for the prefix

# sed -e 2's/.*/PREFIX: &/' /tmp/file
Line One
PREFIX: Line Two
Line Three
Line Four
Line Five

What if you don't have a line number instead you have a pattern name which you want to match and perform this action

There are two ways to do this which would depend completely on your requirement.
1. You can get the specific line number and perform the action
2. You can grep the pattern and then perform the action

For eg:

You can get the line number using below command

# grep -n "Line Three" /tmp/file | cut -d: -f -1
3

now since you know you text is at line number '3' now you can use 'sed' as shown above

OR

you can simply search the pattern and perform the action as shown below

# sed -e 's/Line Three/PREFIX: &/' /tmp/file
Line One
Line Two
PREFIX: Line Three
Line Four
Line Five

 

to make the changes within the same file

# sed -i 's/Line Three/PREFIX: & :SUFFIX/' /tmp/file

 

Append both prefix and suffix at the same time using single command

This can be done using the below command

# sed -e 's/.*/PREFIX: & :SUFFIX/' /tmp/file
PREFIX: Line One :SUFFIX
PREFIX: Line Two :SUFFIX
PREFIX: Line Three :SUFFIX
PREFIX: Line Four :SUFFIX
PREFIX: Line Five :SUFFIX

Leave a Comment