waldauf
waldauf

Reputation: 400

Function in pipe chain

I have this function where input parameters are searched string and input file. Function works with files:

f_highlite() {
    sed -e 's/\($1\)/\o033[91m\1\o033[39m/g' $2
}

Now I would like to use this function in pipe. How does it should be modified?

ps aux | grep java | f_highlite "Xms" -

PS: I'm not sure how to exactly name this question. If you have better suggestion say it. ;]

Upvotes: 1

Views: 128

Answers (2)

Fred
Fred

Reputation: 6995

There are two other approaches that you might want to know about, as not all commands would support the - trick.

The first one is having a function that works on streams and does not take a file as input. You can do that by removing the $2 at the end, and changing how you call the function

f_highlite() {
    sed -e 's/\($1\)/\o033[91m\1\o033[39m/g'
}

f_highlite <"Xms"

This will redirect the content of your file and connect it to the standard input of the function (and hence to that of sed).

The other approach is to keep your function as is (I am reusing a correction to the quoting suggested in another answer), but feed it a file by using process substitution.

f_highlite() {
    sed -e "s/\($1\)/\o033[91m\1\o033[39m/g" "$2"
}

f_highlite < <(<"Xms")

This (conceptually at least) creates a FIFO that has its input fed with the content of your file, and its output connected to the input of the function. The key here is that <(<"Xms") becomes a filename (you can try printing its name to validate that).

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

First, you need to use double quotes, otherwise $1 wouldn't get expanded:

f_highlite() {
    sed -e "s/\($1\)/\o033[91m\1\o033[39m/g" "$2"
}

Btw, you need to make sure that $1 won't contain characters that are understood by sed as syntax elements. For Xms that's fine.


To the topic, you can pass - as the second argument to the function because sed understands - as stdin:

ps aux | grep Java | f_highlite "Xms" -

(thanks @chepner!)

Upvotes: 3

Related Questions