2

I have to use the below bash command in a python script which includes multiple pip and grep commands.

 grep name | cut -d':' -f2  | tr -d '"'| tr -d ','

I tried to do the same using subprocess module but didn't succeed.

Can anyone help me to run the above command in Python3 scripts?

I have to get the below output from a file file.txt.

 Tom
 Jack

file.txt contains:

"name": "Tom",
"Age": 10

"name": "Jack",
"Age": 15

Actually I want to know how can run the below bash command using Python.

    cat file.txt | grep name | cut -d':' -f2 | tr -d '"'| tr -d ','
Peter Parker
  • 77
  • 1
  • 7
  • Possible duplicate of [Execute a bash command with parameter in Python](https://stackoverflow.com/questions/37521778/execute-a-bash-command-with-parameter-in-python) – vahdet Mar 15 '19 at 07:10
  • Is your file json? – Allan Mar 15 '19 at 07:29

2 Answers2

1

This works without having to use the subprocess library or any other os cmd related library, only Python.

my_file = open("./file.txt")
line = True
while line:
    line = my_file.readline()
    line_array = line.split()
    try:
        if line_array[0] == '"name":':
            print(line_array[1].replace('"', '').replace(',', ''))
    except IndexError:
        pass
my_file.close()
Lauro Bravar
  • 373
  • 2
  • 9
0

If you not trying to parse a json file or any other structured file for which using a parser would be the best approach, just change your command into:

grep -oP '(?<="name":[[:blank:]]").*(?=",)' file.txt

You do not need any pipe at all.

This will give you the output:

Tom
Jack

Explanations:

  • -P activate perl regex for lookahead/lookbehind
  • -o just output the matching string not the whole line
  • Regex used: (?<="name":[[:blank:]]").*(?=",)
    • (?<="name":[[:blank:]]") Positive lookbehind: to force the constraint "name": followed by a blank char and then another double quote " the name followed by a double quote " extracted via (?=",) positive lookahead

demo: https://regex101.com/r/JvLCkO/1

Allan
  • 12,117
  • 3
  • 27
  • 51
  • Actually I want to know how can run the below bash command using Python. cat file.txt | grep name | cut -d':' -f2 | tr -d '"'| tr -d ',' – Peter Parker Mar 15 '19 at 08:43