unkaitha
unkaitha

Reputation: 225

Extract the matched regex or delete strings other than the matched regex

I have a file

**data2.l**
I have a car 
its nissan GTR 
this car is super fast

If I want to delete the word "car" from this file I just use

perl -p -i -e "s/car//ig" data2.l

But if I want to keep "car" and delete all other terms other than "car" If I try to just extract the "car" I am just able to extract the complete line containing "car".

**example O/P**
car
car

So can this one-liner be modified a bit to do this task?

Upvotes: 0

Views: 132

Answers (3)

protist
protist

Reputation: 1220

I had some fun with this. All of these options will only print car once, even if it occurs multiple times in the file.

more data2.1 | grep -q 'car' && echo 'car'

more dara2.1 | sed -n 'h;N;$x;$s/.*car.*/car/p'

perl -ne '$i=1 if ~~/car/}{print "car\n" if $i' data2.1

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95252

This Perl does something similar, but all the "car"s on the same line stay on the same line:

  perl -lne 'print join " ", /car\S*/ig if /car/i'

You get this output from steve's example:

car
car123 Car

Upvotes: 2

Steve
Steve

Reputation: 54402

If the word 'car' appears multiple times on each line, this will literally print both times, adding a newline ending:

grep -io "car" file.txt

Input:

i have a car 
its nissan GTR 
this car is super fast Car

Output:

car
car
Car

UPDATE:

grep -ioP "car[^ ]*" file.txt

input:

i have a car 
its nissan GTR 
this car123 is super fast Car

output:

car
car123
Car

Upvotes: 3

Related Questions