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 ','
2

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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 ','

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.