vendredi 4 novembre 2016

How to execute a conditional grep based on a shell function argument?

I have the following function:

function long_command() {
     cat $1 | grep -vE '[a-fA-F0-9]{5}' | \
     cat -n | sed -e 's/    / /g' | \
     sed -e 's/^  *//g' | \
     sort -k 3,3 -k 1n,1n | \
     uniq -f 2 | \
     sed -e 's/^[0-9]\{1,\} //' | \
     grep -Ev '^\s*PATTERN\s+' | \
     cat -n
}

The first part of the command filters some stuff. In the last part of the command I would like to filter using grep -Ev '^\s*PATTERN\s+' only if the argument $2 is set and equals let's say VALUE, before piping to the last cat -n. How can I do that?

This doesn't work:

function long_command() {
     cat $1 | grep -vE '[a-fA-F0-9]{5}' | \
     cat -n | sed -e 's/    / /g' | \
     sed -e 's/^  *//g' | \
     sort -k 3,3 -k 1n,1n | \
     uniq -f 2 | \
     sed -e 's/^[0-9]\{1,\} //' | \
     if [ "$2" -eq "VALUE" ];  then grep -Ev '^\s*PATTERN\s+'; fi | \
     cat -n
}

I get an error:

-bash: [: : integer expression expected

What't the correct way to use an if and pipe the result of the if to cat -n?

Thanks for the attention.

Aucun commentaire:

Enregistrer un commentaire