0

I have a list of file names where I wish to remove items containing different letters or strings.

If I run

cat <file> | grep -Ev 'P1|P2'

in a bash shell it works.

but in a script

#!/bin/bash
...
PLIST="f,d"    #test example
GARG="'$(echo $PLIST | tr "," "|" |tr -d "\n")'"
cat $FNAME | grep -Ev $GARG

It doesn't work. It just lists all lines in the file.

I've tried to echo $GARG and the value is: 'f|d'

The problem is the way I generate GARG.

GARG=$(echo $PLIST | tr "," "|" |tr -d "\n")

This works, but if I echo $GARG the value is: f|d without the ' ' characters.

I don't understand why it doesn't work with the ' ' characters but works without them?

  • We can't tell which of many possible things can be going wrong with what you have given us. Please *EDIT* your question and show us the actual script, especially the parts where you define your variables. You say you echoed them, great, show us! Also show us how you run the script, and provide a minimal example input that reproduces the problem. – terdon Dec 18 '22 at 18:01
  • By the way, this won't be relevant but just so you know, cat file | grep is a classic example of what is called "a useless use of cat", often abbreviated to UUoC in the *nix world. Grep can read files, there is no reason to cat them: grep -Ev 'P1|p2' file works just fine. – terdon Dec 18 '22 at 18:02
  • 1
  • 1
    If the file does not contain the pattern, then yes grep -v acts like cat. Are you certain the file contains P1 or P2? – glenn jackman Dec 18 '22 at 18:17
  • @glennjackman I've moved my answer to the question and deleted the answer. I'd really appreciate if you could elaborate on your comment regarding the quote characters? – user3866319 Dec 19 '22 at 19:15

1 Answers1

1

To print the lines of the file whose path is stored in $FNAME not matching the extended regular expression stored in in $GARG, in Bourne-like shells (such as bash), the syntax would be:

FNAME=/path/to/some/file
GARG='P1|P2'
grep -Eve "$GARG" < "$FNAME"

To remove the lines that contain any of the elements in an array (assuming those elements don't contain newline character and that the array is not empty), in ksh93-like shells (such as bash):

list=(P1 P2)
FNAME=/path/to/some/file
grep -Fv "${list[@]/#/-e}" < "$FNAME"

Or:

list=(P1 P2)
FNAME=/path/to/some/file
printf '%s\n' "${list[@]}" | grep -Fvf - -- "$FNAME"

(that one assumes $FNAME is not -)