How to add the text before the line in whole file?

Solution 1:

If you want the original to be intact:

sed 's/^/127.0.0.1 /' domain.txt > new_domain.txt

Solution 2:

GUI answer using GEdit

  1. Open up your file in Gedit. Let's say I want to add '127.0.0.1 ' to the beginning of all lines in this text file.

enter image description here

  1. Using search and replace feature, search for \n and replace it with \n127.0.0.1 then click Replace all button as shown below:

enter image description here

  1. This is your result:
    Disclaimer: You will have to manually enter the replace with text 127.0.0.1 at the beginning of the first line.

enter image description here

Solution 3:

You can achieve that with sed in the following way:

sed -i 's/^/127.0.0.1 /' /path/filename.txt

Best make a backup of the file before, I'm right now not sure if you need to escape the space or not. To make a backup directly when you run sed you can use the following line:

sed -i_bak -e 's/^/127.0.0.1 /' /path/filename.txt

A bit more information about sed you can find here.

Solution 4:

awk is a good option to this issue. Explaining in two examples:

# Let's consider a file domain.txt with lines like this:
# <domain> <user> <user> ....
# Ex: domain.zzz.yy user01 user02

# Extracting the first field of each line
awk '{ print "127.0.0.1 " $1;}' domain.txt

# produces: 127.0.0.1 domain.zzz.yy
# filter only first field $1=domain.zzz.yy
# $1: first field, $2: second field, and so on

# Extracting the whole line
awk '{ print "127.0.0.1 " $0;}' domain.txt

# produce: 127.0.0.1 domain.zzz.yy user01 user02
# $0: whole line