0

I'm trying to apply positional arguments to make it easier to copy/paste strings when looking for content in files of my project.

This command works fine:

grep myString -R .

but this command does not:

grep "$1" -R . myString

I tried several combinations, including single quotes, using brackets etc.

Appreciate any advises on how to search for a string recursively on a project.

Edit: I'm trying to use this command directly from the terminal (not on a shell script)

4
  • 1
    Are you directly working with the command line? Or are you running the grep command inside a shell script and running it from your terminal? Commented Mar 17, 2022 at 2:45
  • 2
    Note the syntax of grep: grep [OPTION...] PATTERNS [FILE...]. It is unclear what the variable $1 contains, please elaborate Commented Mar 17, 2022 at 2:57
  • I'm trying to use this directly on the command line @EdgarMagallon Commented Mar 17, 2022 at 3:26
  • I'm trying to make myString occupy the "$1" placeholder inline Commented Mar 17, 2022 at 3:26

1 Answer 1

2

Your question is pretty unclear, and I'm not sure I'm understanding it properly. If I am misunderstanding wrongly, I apologize.

However, if I understand you right, you want to be able to use grep in a way that puts the search pattern at the end of the command, because it's more convenient to copy and paste to the end of a command than it is to copy and paste to the beginning of the command, especially if you're running the command multiple times with different search patterns?

Unfortunately, grep's syntax requires the search pattern to come before specifying the search location.

As I see it, there are two solutions. The first is to define a function:

You could put this in your .bashrc, or just define it once for the session:

recgrep() {
    grep "$1" -R .
}

You could then call the function like this:

recgrep myString

And it would do a recursive search in the current folder for mystring.

The other would be to use ripgrep, which recursively searches by default, instead of GNU grep. It's also faster than GNU grep in my experience.

rg myString
2
  • Sorry I accidentally posted a half-finished version of this answer, but then finished it with an edit. I'm just clumsy.
    – frabjous
    Commented Mar 17, 2022 at 4:00
  • Thank you for clarifying. This is exactly what I was trying to ask. Forgive my English skills, and thank you for your answer! I will look for ripgrep Commented Mar 17, 2022 at 4:17

You must log in to answer this question.

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