ayasha
ayasha

Reputation: 1251

Grep (Bash) error

I have a file like this called new.samples.dat

-4.5000000000E-01 8.0000000000E+00 -1.3000000000E-01
5.0000000000E-02 8.0000000000E+00 3.4000000000E-01
...

I have to search all this numbers of this file in another file called Remaining.Simulations.dat and copy them in another file. I did like this

for sample_index in $(seq 1 100)
do
  sample=$(awk 'NR=='$sample_index'' new.samples.dat)
  grep "$sample" Remaining.Simulations.dat >> Previous.Training.dat
done

It works almost fine but it does not copy all the $sample into Previous.Training.dat even if I am sure that these are in Remaining.Simulations.dat This errors appear

grep: invalid option -- '.'
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

Do you have any idea how to solve it?Thank you

Upvotes: 0

Views: 2924

Answers (2)

jaypal singh
jaypal singh

Reputation: 77075

With awk you can try something like:

awk '
NR==FNR {
    for (i=1;i<=NF;i++) {
        numbers[$i]++
    }
    next
}
{
    for (number in numbers)
        if (index ($0,number) > 0) {
            print $0

    }
}' new.samples.dat Remaining.Simulations.dat > anotherfile

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881093

It's because you're trying to grep for something like -4.5 and grep is treating that as an option rather than a search string. If you use -- to indicate there are no more options, this should work okay:

pax> echo -4.5000000000E-01 | grep -4.5000000000E-01
grep: invalid option -- '.'
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

pax> echo -4.5000000000E-01 | grep -- -4.5000000000E-01
-4.5000000000E-01

In addition, if you pass the string 7.2 to grep, it will match any line containing 7 followed by any character followed by 2 since:

  1. Regular expressions treat . as a special character; and
  2. Without start and end markers, 7.2 will also match 47.2, 7.25 and so on.

Upvotes: 5

Related Questions