Skip to content
Advertisement

How can I delete a specific text in a text file

I have a text file :

192.168.47.100 computer
192.168.47.101 phone
192.168.47.1 computer3
192.168.47.50 computer2

and I want to delete 192.168.47.1 line

I tried

while read line
do
    IPTemp="$line"
    ex -s +"g/$IPTemp/d" -cwq $1
done < IPLib.txt

but output is :

192.168.47.50 computer 3

I tried sed 's/192.168.47.1//g' but again output is :

00 computer
01 phone
computer3
192.168.47.50 computer2

I searched on google but but I am not able to find the right one.

Advertisement

Answer

The problem is that your pattern matches 3 lines in your data. You need to end it with $. Also, if you use sed‘s replace (s/) you end up with empty lines. Use delete:

$ sed '/192.168.47.1$/d' file
192.168.47.100
192.168.47.101
192.168.47.50

In awk:

$ awk '!/192.168.47.1$/' file
192.168.47.100
192.168.47.101
192.168.47.50

another in awk where the whole first column is compared to a string, not using regex (thanks @Kent for pointing out):

$ awk '$1!="192.168.47.1"' file
192.168.47.100
192.168.47.101
192.168.47.50

and using grep:

$ grep -v 192.168.47.1$ file
192.168.47.100
192.168.47.101
192.168.47.50

Edit: Apparently you changed the data. Now you need to end the pattern with a space:

$ sed '/192.168.47.1 /d' file2
192.168.47.100 computer
192.168.47.101 phone
192.168.47.50 computer2

and in awk:

$ awk '!/192.168.47.1 /' file2
192.168.47.100 computer
192.168.47.101 phone
192.168.47.50 computer2

and grep:

$ grep -v 192.168.47.1  file2
192.168.47.100 computer
192.168.47.101 phone
192.168.47.50 computer2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement