Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to process input from pipe

Tags:

bash

shell

I'm trying to write a bash-function to return a specific line of piped output by its number. Currently the full command looks like this:

mdfind 'my_search_string' | sed "2q;d"

That would return the 2nd line of output from the mdfind-command.

I'm trying to turn sed "$1q;d" into a function that gets assigned as an alias.

How can I process the piped input?

like image 719
Hedge Avatar asked Jan 12 '23 11:01

Hedge


1 Answers

To return the second line of output, do this:

... | sed -ne 2p

And to use it as a function:

function print_2nd_line {
    sed -ne 2p
}

mdfind 'my_search_string' | print_2nd_line

You could also choose shorter names like p2 at your option.

The function can also be customized to be capable of printing second line from specified files like:

function print_2nd_line {
    sed -ne 2p -- "$@"
}

print_2nd_line file
... | print_2nd_line  ## Still could be used like this.

By the way the more efficient version would be

sed -ne '2{p;q}'

UPDATE

As suggested by Charles Duffy, you could also use this format for POSIX compatibility. Actually it's also compatible with all shells based from the original System V sh.

print_2nd_line() {        
    sed -ne '2{p;q}' -- "$@"
}

Also, if you want to pass a custom line number to your function, you could have:

print_2nd_line() {
    N=$1; shift
    sed -ne "${N}{p;q}" -- "$@"
}

Where you can run it as:

... | print_2nd_line 2  ## Still could be used like this.

Or

print_2nd_line 2 file
like image 59
konsolebox Avatar answered Jan 22 '23 09:01

konsolebox