簡體   English   中英

cat,grep和cut-翻譯成python

[英]cat, grep and cut - translated to python

也許有足夠的問題和/或解決方案,但是我只是無法解決這個問題:我在bash腳本中使用了以下命令:

var=$(cat "$filename" | grep "something" | cut -d'"' -f2)    

現在,由於某些問題,我必須將所有代碼轉換為python。 我以前從未使用過python,而且我完全不知道如何執行postet命令的功能。 有什么想法如何用python解決嗎?

您需要更好地了解python語言及其標准庫才能翻譯表達式

cat“ $ filename” :讀取文件cat "$filename"並將內容轉儲到stdout

| :管道將上一個命令的stdout重定向並將其饋送到下一個命令的stdin

grep的“東西” :搜索與正則表達式something純文本數據文件(如果指定的),或在標准輸入,並返回所述匹配線。

cut -d'“'-f2 :使用特定的定界符分割字符串,並從結果列表中索引/拼接特定字段

相當於Python

cat "$filename"  | with open("$filename",'r') as fin:        | Read the file Sequentially
                 |     for line in fin:                      |   
-----------------------------------------------------------------------------------
grep 'something' | import re                                 | The python version returns
                 | line = re.findall(r'something', line)[0]  | a list of matches. We are only
                 |                                           | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2    | line = line.split('"')[1]                 | Splits the string and selects
                 |                                           | the second field (which is
                 |                                           | index 1 in python)

結合

import re
with open("filename") as origin_file:
    for line in origin_file:
        line = re.findall(r'something', line)
        if line:
           line = line[0].split('"')[1]
        print line

在Python中,沒有外部依賴性,它是這樣的(未經測試):

with open("filename") as origin:
    for line in origin:
        if not "something" in line:
           continue
        try:
            print line.split('"')[1]
        except IndexError:
            print

您需要使用os.system模塊來執行shell命令

import os
os.system('command')

如果要保存輸出以供以后使用,則需要使用subprocess模塊

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

要將命令翻譯成python,請參考以下內容:

1)可選的cat命令已打開, 請參見此 下面是示例

>>> f = open('workfile', 'r')
>>> print f

2)grep命令的替代方法請參考

3)剪切命令的替代方法請參考

您需要在文件行上循環,需要了解字符串方法

with open(filename,'r') as f:
    for line in f.readlines():
        # python can do regexes, but this is for s fixed string only
        if "something" in line:
            idx1 = line.find('"')
            idx2 = line.find('"', idx1+1)
            field = line[idx1+1:idx2-1]
            print(field)

並且您需要一種將文件名傳遞給python程序的方法 ,當您使用它時,也許還需要搜索字符串...

為了將來,請嘗試提出更集中的問題,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM