Operating System - HP-UX
1753844 Members
7468 Online
108806 Solutions
New Discussion юеВ

find and remove a string(and its line)

 
SOLVED
Go to solution
sekar_1
Advisor

find and remove a string(and its line)

Hi,
in vi editor i used :%s/searchString/replace/g
but i would like to know how to remove that whole line of the search string.

i did :set list and it shows $ in the end of every line. but when i used $ like :%s/searchString$//g
its not working.
14 REPLIES 14
Danny Petterson - DK
Trusted Contributor

Re: find and remove a string(and its line)

Hm - sorry, but I suck a bit on sed and vi - whay dont you just chat and use "grep -v" and then pipe the output into a new file, and afterwards rename it to the original file?
sekar_1
Advisor

Re: find and remove a string(and its line)

hmmm...not so simple. the file has around 2000 lines.

say this is my file:
----------
1
1
2
3
4
5
6
7
-----------
from this file i would like get a new file like this one:(search strings 3 and 5 removed with its lines)
-----------
1
1
2
4
6
7
------------
sekar_1
Advisor

Re: find and remove a string(and its line)

sorry,...the line intentions are gone.

ok, question is how to remove carriage returns or newline charactors in a file??
AwadheshPandey
Honored Contributor

Re: find and remove a string(and its line)

cat file|sed '/search string/ d'
regards, Awadhesh
It's kind of fun to do the impossible
AwadheshPandey
Honored Contributor

Re: find and remove a string(and its line)

VK2COT
Honored Contributor
Solution

Re: find and remove a string(and its line)

Hello,

When you are in command mode in vi(1),
command "set list" displays
End-Of-Line characters as "$" sign.

To remove certain lines from file,
you can simply:

# egrep -v "^3|^5" origfile > newfile

or

# awk '! /^3|^5/ {print}' origfile > newfile

Many other ways exist.

Cheers,

VK2COT
VK2COT - Dusan Baljevic
James R. Ferguson
Acclaimed Contributor

Re: find and remove a string(and its line)

Hi Sekar:

Why not 'sed'?:

# sed -e '/3/d;/5/d' file

...removes any lines that have a 3 or a 5 somewhere on them (your example).

Whereas:

# sed -e '3d;5d' file

...removes line #3 and line #5 if that were your objective.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: find and remove a string(and its line)

>but i would like to know how to remove that whole line of the search string.

You need:
:g/string/d

If you only want to remove "string" from a limited range, you can use:
:lineN,lineMg/string/d

>(search strings 3 and 5 removed with its lines)

You can do two passes or you can create a complex search string.

>question is how to remove carriage returns or newline characters in a file??

You can use "j" to join lines. You can use this to delete empty lines:
:g/^$/d


sekar_1
Advisor

Re: find and remove a string(and its line)

thanks a lot admins. almost got it.