user8115103
user8115103

Reputation:

Sed an empty String and replace it

i like to know how to replace an empty result with abc for example in a long pipe.

So if i filter a big .txt file with sed and grep and other stuff. Is there a way that at the end of this pipe i replace an empty result? So that if i dont find my pattern in the file i get an abc

I work in sh and want it included in the long pipe without using special stuff. I tried:

cat myfile.txt | grep 'blabla.*' | sed 's/^$/abc/g'

and

`cat myfile.txt | grep 'blabla.*' | sed 's//abc/g'`

.

Upvotes: 1

Views: 3494

Answers (4)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed '/blabla/q;$!d;cabc

If string found print it and quit. Otherwise at end of the file change the last line to abc.

Upvotes: 0

Walter A
Walter A

Reputation: 19982

Use

tee >(read || echo "abc")

Explanation: You can look for empty input with

pipeline_with_sed | grep -q . || echo "abc"

This has different problems.
When the output has empty lines, it is not empty. So you should test for any data:

pipeline_with_sed | read || echo "abc"

This will give your "abc" for empty output of the pipeline.
Now you want to see the original output when something is there.
With tee you can redirect the output to a file and another process.
And redirecting to a file can also be replaced to writing to another program.

pipeline_with_sed | tee >(read || echo "abc")

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157947

I would use a single awk command:

awk '/blabla/{print;found=1}END{if(!found){print "not found"}}' myfile.txt

Upvotes: 2

William Pursell
William Pursell

Reputation: 212198

I think you are saying that if grep produces no matches, you want to see "abc". I don't know if this counts as "special stuff", but you can do:

grep 'blabla.*' myfile.txt || echo abc

This will work fine in a pipeline:

cmd1 | cmd2 | { grep 'blabla.*' || echo abc; } | cmd3 | cmd4

In fact, it also works just fine to put more complex logic in a pipeline, although you don't see this style very often:

cmd1 |
if grep blabla.*; then : ; else echo abc; fi |
cmd2

Upvotes: 7

Related Questions