Nathan Pk
Nathan Pk

Reputation: 749

sed to grep strings between two patterns

I have a list of expressions in a file script.sh like

    1  name1  Pending    flag0
    2  name2  Completed  flag1
    3  name3  Completed  flag-

etc.,

I would like to grep specific status between "1" and "pending" (i.e name1).

I tried with this command

    var="1"

    cat script.sh |sed -n "s/^${var}\(.*\)Pending.*$/\1/gp"

this doesn't return anything.

Upvotes: 2

Views: 3173

Answers (4)

Chris Seymour
Chris Seymour

Reputation: 85815

This in how you do it using : grep -Po '(?<=1).*(?=Pending)' file

$ cat file
    1  name1  Pending    flag0
    2  name2  Completed  flag1
    3  name3  Completed  flag-

$ grep -Po '(?<=1).*(?=Pending)' file
  name1  

Here is displaying only the matches that followed a 1 and precede the word Pending.

Note: this is using positive lookahead and lookbehind.

Upvotes: 2

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Your solution needs only a minor modification:

var="1"

cat script.sh | sed -n "/^${var}.*Pending/{s/^${var}\(.*\)Pending.*$/\1/;p;}"

Upvotes: 0

sampson-chen
sampson-chen

Reputation: 47277

How about an solution?

awk '{for (i=1; i<=NF; i++) {if ($i == "Pending") {print $(i-1)}}}' input_file

Upvotes: 0

VB9-UANIC
VB9-UANIC

Reputation: 330

    sed -n 's/^1\(.*\)Pending.*$/\1/gp'

you got extra slash at the beginning

Upvotes: 0

Related Questions