double_j
double_j

Reputation: 1706

Trouble with if command using grep in Terminal

How do I do something like this?

"input" | \

if
grep -E 'phone_and_fax":"Phone: .*  Fax:'
then
sed 's/phone_and_fax":"Phone:/|/g' | \
sed 's/  Fax:/|/g' | \
sed 's/original_license_date":"Original License Date:/|/g'
elif
grep 'phone_and_fax":"Phone: '
then
sed 's/phone_and_fax":"Phone:/|/g' | \
sed 's/original_license_date":"Original License Date:/||/g'
elif
grep '  Fax:'
then
sed 's/phone_and_fax":"Phone:/||/g' | \
sed 's/  Fax:/|/g' | \
sed 's/original_license_date":"Original License Date:/|/g'
else
sed 's/phone_and_fax":"Phone:/||/g' | \
sed 's/original_license_date":"Original License Date:/|/g'
fi | \

"continue script"

The point of what is being replaced or what is being looked for doesn't really matter. What I am trying to do is use some piping to handle some text, but if it runs across a certain pattern using grep with regex, then it needs to change what it will replace with that particular instance. But the grep should not change the output of the piping.

Upvotes: 1

Views: 183

Answers (1)

John1024
John1024

Reputation: 113834

sed already has grep-like tests built-in to its syntax:

For example, take this pseudo-code:

if grep -E 'some.*xt'; then sed 's/some/SOME/g'; fi

It can be translated into a single call to sed. Observe:

$ echo some text | sed '/some.*xt/ s/some/SOME/g'
SOME text

Versus:

$ echo some test | sed '/some.*xt/ s/some/SOME/g'
some test

Longer example

Consider this pseudo-code:

if
grep -E 'some.*xt'
then
sed 's/some/SOME/g'
elif
grep 'is'
then
sed 's/is/IS/g'
fi | \
sed 's/This/""/g'

The equivalent sed statement is:

sed '/some.*xt/ {s/some/SOME/g; b fi}; /is/ s/is/IS/g; :fi; s/This/""/g'

The elif part of the pseudo-code is translated here to a branch statement. If the condition /some.*xt/ matches, then the substitution s/some/SOME/g is performed and b fi tells sed to jump to the label fi. This does the logical equivalent of the elif statement.

Examples illustrate this in operation:

$ echo "some text This is" | sed '/some.*xt/ {s/some/SOME/g; b fi}; /is/ s/is/IS/g; :fi; s/This/""/g'
SOME text "" is
$ echo "some test This is" | sed '/some.*xt/ {s/some/SOME/g; b fi}; /is/ s/is/IS/g; :fi; s/This/""/g'
some test ThIS IS

Upvotes: 1

Related Questions