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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With