Reputation: 46
Is there a way to conditionally pipe the output of a command through sed, in a bash script? Depending upon a script option, I either want to pipe the output of a long pipe through sed, or omit the pipe through sed. Currently I'm doing
if [ $pipeit ]; then
sed_args='/omit this line/d'
else
sed_args='/$^/d' # pass-thru (what's a better sed pass thru?)
fi
some_cmd | sed "$sed_args"
Upvotes: 2
Views: 721
Reputation: 2868
By default sed
prints all lines:
if [ $pipeit ]; then
sed_args='/omit this line/d'
else
sed_args="" # pass-thru
fi
some_cmd | sed "${sed_args}"
There is this other tested solution:
some_cmd | if [ $pipeit ]; then
sed "/omit this line/d"
else
sed ""
fi
cat
could be used instead of the sed ""
Finally, a string can be built and executed using eval
.
some_cmd='printf "foo\n\nbar\n"'
if [ $pipeit ]; then
conditional_pipe='| sed "/foo/d"'
else
conditional_pipe=""
fi
eval "${some_cmd}" "${conditional_pipe}"
If some_cmd
is complex it migth be tricky to build a string that would behave as expected with eval
.
First solution for history
Using an impossible match with sed
would make it print all lines to stdout:
$ printf "foo\n\nbar\n" | sed "/./{/^$/d}"
foo
bar
/./
selects a line with at least one char.
/^$/
selects an empty line.
Upvotes: 1
Reputation: 158060
I would keep it as simple as:
if [ $pipeit ]; then
some_cmd | sed '/omit this line/d'
else
some_cmd
fi
Why should you call sed
if you don't need it? Just for your information, a possible sed command that does not change the input would be sed -n p
Btw, if some_cmd
is kind of a large beast and you want to avoid duplicating it, wrap it into a function.
Upvotes: 3