Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and remove line from file in Unix?

Tags:

file

find

unix

line

I have one file (for example: test.txt), this file contains some lines and for example one line is: abcd=11 But it can be for example: abcd=12 Number is different but abcd= is the same in all case, so could anybody give me command for finding this line and remove it?

I have tried: sed -e \"/$abcd=/d\" /test.txt >/test.txt but it removes all lines from my file and I also have tried: sed -e \"/$abcd=/d\" /test.txt >/testNew.txt but it doesn't delete line from test.txt, it only creates new file (testNew.txt) and in this file it removes my line. But it is not what I want.

like image 715
Adam Avatar asked Dec 22 '22 00:12

Adam


1 Answers

Based on your description in your text, here is a cleaned-up version of your sed script that should work.

Assuming a linux GNU sed

sed -i '/abcd=/d' /test.txt 

If you're using OS-X, then you need

sed -i "" '/abcd=/d' /test.txt 

If these don't work, then use old-school sed with a conditional mv to manage your tmpfiles.

sed '/abcd=/d' /test.txt > test.txt.$$ && /bin/mv test.txt.$$ test.txt

Notes:

Not sure why you're doing \"/$abcd=/d\", you don't need to escape " chars unless you're doing more with this code than you indicate (like using eval). Just write it as "/$abcd=/d".

Normally you don't need '-e'

If you really want to use '$abcd, then you need to give it a value AND as you're matching the string 'abcd=', then you can do

 abcd='abcd='
 sed -i "/${abcd}/d" /test.txt 

I hope this helps.

like image 108
shellter Avatar answered Dec 29 '22 11:12

shellter