Johnathon
Johnathon

Reputation: 43

How to grep and cut at the same time

Having trouble with grepping and cutting at the same time I have a file test.txt. Inside the file is this syntax

File: blah.txt Location: /home/john/Documents/play/blah.txt
File: testing.txt Location /home/john

My command is ./delete -r (filename), say filename is blah.txt.

How would i search test.txt for blah.txt and cut the /home/john/Documents/play/blah.txt out and put it in a variable

Upvotes: 4

Views: 22699

Answers (3)

Loukan ElKadi
Loukan ElKadi

Reputation: 2867

Try this one ;)

filename=$(grep 'blah.txt' test.txt | grep -oP 'Location:.*' | grep -oP '[^ ]+$')
./delete $filename

Upvotes: 0

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

grep -P "^File: blah\.txt Location: .+" test.txt | cut -d: -f3

Upvotes: 8

dimba
dimba

Reputation: 27581

Prefer always to involse as less as possible external command for your task.

You can achive what you want using single awk command:

awk '/^File: blah.txt/ { print $4 }' test.txt

Upvotes: 5

Related Questions