0

Have a nice day I have got text file (zz.txt):

Chemical name
3-Aminopropane-1-sulphonic acid
Synonym(s)
--
Homotaurine * Tramiprosate
--
Chemical name
Common name and synonyms
...

I have variable s="Homotaurine * Tramiprosate"; I try to (un)select text of this variable from text file:

s="Homotaurine * Tramiprosate"; cat zz.txt | grep -i "$s"
s="Homotaurine * Tramiprosate";cat zz.txt | sed -ne "/$s/p"

Does not work. But if I change $s to, for instance, "Chemical name", everything ok, grep and sed work correctly and similarly. Variable $s received from another text file. Next time it could contain asterisk or not. Yes I realize that asterisk is very special character. How can I solve my task with sed/grep? And additional question - what others similar characters could create headache?

6
  • this is not a regular expression as understood by these tools, so in that mode, they are not what you need, unless you're searching for lines that contain Homotaurine, follow by two or more spaces (and nothing else), followed by Tramiprosate. I don't think that's the case. What do you want to find? It's sadly not clear to me. Commented Sep 20, 2023 at 10:01
  • For grep, you can use -F to use fixed strings instead of regexes. For sed, it's much more complex. I'd probably switch to Perl which can help you with its quotemeta function.
    – choroba
    Commented Sep 20, 2023 at 10:06
  • I just want to write command cat zz.txt | grep/sed/... "$s" and see output "Homotaurine * Tramiprosate"
    – Alex Den
    Commented Sep 20, 2023 at 10:07
  • choroba, it that I want to get! hurraaa!!!! thank you!
    – Alex Den
    Commented Sep 20, 2023 at 10:10
  • Try s="Homotaurine \* Tramiprosate";cat zz.txt | sed -ne "/$s/p"
    – K-attila-
    Commented Sep 20, 2023 at 14:43

1 Answer 1

3

For grep, you can use -F to use fixed strings instead of regexes. For sed, it's much more complex. I'd probably switch to Perl which can help you with its \Q/quotemeta function.

#!/bin/bash
s="Homotaurine * Tramiprosate"; grep -Fi -- "$s" zz.txt
s="Homotaurine * Tramiprosate"; s=$s perl -ne 'print if /\Q$ENV{s}/' -- zz.txt
2
  • choroba, thank you very much. as I heard perl is powerful tool but for me grep/sed/tr/cat/sort is more than enough. it is more or less understandable for me.
    – Alex Den
    Commented Sep 20, 2023 at 10:15
  • If you want to match a fixed substring with Perl, you might also choose to use index() (just like in awk). I also notice that the user in the question may want to use -x with grep, unless their query string is supposed to be used as a substring.
    – Kusalananda
    Commented Sep 21, 2023 at 10:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .