How to find and remove a line from a file on Unix?
I have one file (for example: test.txt), this file contains some lines and for example one line: abcd = 11 But it could be for example: abcd = 12 The number is different but abcd = is the same in all cases, so what can anyone give me a command to search for this line and remove it?
I tried:, sed -e \"/$abcd=/d\" /test.txt >/test.txt
but it removes all lines from my file, and I also tried:, sed -e \"/$abcd=/d\" /test.txt >/testNew.txt
but it doesn't remove the line from test.txt, it only creates a new file (testNew.txt) and my line is deleted in that file. But that's not what I want.
source to share
Based on your description in your text, here's a cleaned up version of your sed script that should work.
Assuming linux GNU sed
sed -i '/abcd=/d' /test.txt
If you are using OS-X you need
sed -i "" '/abcd=/d' /test.txt
If they don't work, 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 are doing \"/$abcd=/d\"
, you don't need to escape characters "
unless you are doing more with this code than you indicate (using for example eval
). Just write it like "/$abcd=/d"
.
You usually don't need '-e'
If you really want to use '$ abcd then you need to give it an AND value since you are matching the string' abcd = 'then you can do
abcd='abcd='
sed -i "/${abcd}/d" /test.txt
Hope this helps.
source to share
As far as I know, this command can be used to create another file with lines deleted. Now that we have another file, we can rename that file and delete the original file if we want. You just need to do it
grep -v '^\$abcd=' test.txt > tmp.txt
now tmp.txt will have content
a
b
ab
ac
$abcd
ab
a
x
If you want you can rename it to test.txt after removing test.txt
source to share