-2

I would like to grep the pattern and return it to a variable, for multiple files, I know how to do it using bash, but now I want to realize it in python.

In bash, I can do something like this

for i in {1..3}
do
  result=$(grep "pattern" folder/name-${i}/out)
done

However, I'm not sure how to do it in Python. I tried:

for i in range(1,4):
    name = 'name-' + str(i)
    result = subprocess.check_output("grep 'pattern' folder/{name}/out", shell=True)

It returns error grep: folder/{name}/out: No such file or directory

Does anyone know how to fix it?

abhigyanj
  • 2,355
  • 2
  • 9
  • 29
xinshou
  • 37
  • 4
  • 1
    The error explains itself, `folder/{name}/out` is not a valid path – abhigyanj Jan 04 '21 at 06:10
  • You missed an `f` before the string to make it an f-string. – Klaus D. Jan 04 '21 at 06:12
  • The variable in your string is not resolved to the variable. You need to format the string. Also if you want to solve it "more" in Python: https://regex101.com/ There is a Python code generator on the website. Because you are still doing the regex work in sh. – Tin Nguyen Jan 04 '21 at 06:17
  • 1
    Running `grep` from Python is almost always easy to avoid by doing the regex search in Python itself. Avoiding an external process is usually a performance win, and often, you can optimize the overall flow by doing things natively. In brief; `import re; with open(f'folder/{name}/out') as thing: result = [line for line in thing if re.match('pattern', line)]` – tripleee Jan 04 '21 at 06:32

3 Answers3

0

You forgot to put an f before "grep 'pattern' folder/{name}/out". So you can use:

for i in range(1, 4):
    name = 'name-' + str(i)
    result = subprocess.check_output(f"grep 'pattern' folder/{name}/out", shell=True)

Or you can use str.format():

for i in range(1, 4):
    name = 'name-' + str(i)
    result = subprocess.check_output("grep 'pattern' folder/{name}/out".format(name=name), shell=True)
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
0
for i in range(1,4):
    name='name-'+str(i)
    result=subprocess.check_output("grep 'pattern' folder/%s/out" % name, shell=True)

or with f before your command:

result = subprocess.check_output(f"grep 'pattern' folder/{name}/out", shell=True)
Synthase
  • 5,849
  • 2
  • 12
  • 34
0

You need a f before the string to make it a f-string:

for i in range(1, 4):
    name = 'name-' + str(i)
    result = subprocess.check_output(f"grep 'pattern' folder/{name}/out", shell=True)

Or you could do % string formatting:

for i in range(1, 4):
    name = 'name-' + str(i)
    result = subprocess.check_output(f"grep 'pattern' folder/%s/out" % name, shell=True)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114