Add at beginning and end of each line for a file

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file::Q

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename



This example shows how to add a character to the beginning of each line using a sed command and bash shell.
Let’s create example file.txt with some text:

add 
character
at the
beginning of
each line

Add character at the beginning of each line using sed command. For example to add # in front of each line we can use sed command with following syntax:

$ sed 's/^/#/' file.txt
#add
#character
#at the
#beginning of
#each line

replace # with ‘ ‘ ( space ) to add space in front of each line:

$ sed 's/^/ /' file.txt
 add
 character
 at the
 beginning of
 each line

Redirect the output produced by sed command to save it to a file:

$ sed 's/^/ /' file.txt  > new-file.txt
$ cat new-file.txt
 add
 character
 at the
 beginning of
 each line
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s