# AWK and Python CODE 對比 ## Example 1 Read Special Field from File ## 範例1從檔案讀取特定欄位 ##### Awk Code {#awk-code} ``` awk -F: '{ print $1 } ' /etc/passwd ``` ##### Python code {#python-code} ``` import os #first step to open File with open('/etc/passwd' , 'r') as passfile: #second step using loop to read each line. for line in passfile: #third step to read special filed from pass line.split(':')[0] #as awk -F: #But in python first position is 0 not 1 ``` --- ## Example 2 Read special Number of rows from file ## 範例2 在檔案中讀取特定行數的的資料 ##### Awk Code {#awk-code-example3} ``` awk -F: 'NR==1 {print $1 } ' /etc/passwd ``` #### Python Code {#python-code-example2} ``` import os row=2 #first step to open File with open('/etc/passwd' , 'r') as passfile: #second step using loop to read each line. for idx,lines in enumerate(passfile): #third step to read special filed from pass if idx == row: print(lines.split(':')[0] ) ``` --- ## Example3 list length greate special size ## 列出長度大於某個數值的row ##### Awk Code {#awk-code_1} ``` awk 'length > 72' /etc/passwd ``` ##### Python code {#python-code_1} ``` import os rowlength=72 #first step to open File with open('/etc/passwd' , 'r') as passfile: #second step using loop to read each line. for line in passfile: if line.legth() > rowlength: print(line) ``` --- ## Example 4 print each line length from file {#example-4-print-each-line-length-from-file} ## 列出每一行的長度 #### Awk code ``` awk '{print length($2)}' /etc/passwd ``` #### Python code ``` import os row=2 #first step to open File with open('/etc/passwd' , 'r') as passfile: #second step using loop to read each line. #for idx,lines in enumerate(passfile): for line in passfile: #third step to read special filed from pass print(len(line.split(':')[0])) #as awk -F: #But in python first position is 0 not 1 th ``` --- ## Example 5 Revese Order {#example-5-revese-order} ## 將資料作反序 #### Awk code ``` awk -F: '{ for (i = NF; i > 0; --i) print $i }' /etc/passwd ``` #### Python code Reference from : [Python And C compare](http://www.saltycrane.com/blog/2009/04/how-reverse-words-sentence-using-python-and-c/) ``` import os #first step to open File with open('/etc/passwd' , 'r') as passfile: for line in passfile: #Split word string and use reversed func #after split() word is list type not string. word=line.split(':') result=" ".join(reversed(word)) print(result) ``` --- ## Example 6 Using Awk to summary a field from all line. ## 作SUMMARY #### Awk code ``` awk -F: '{s += $4} END { print "sum is ", s }' /etc/passwd ``` #### Python code ``` import os sum=0 with open('/etc/passwd' , 'r') as passfile: #second step using loop to read each line. for line in passfile: i =line.split(':')[3] sum = sum + int(i) print(sum) ``` Example 7 Using Regex to search a string in the file ### Awk Code ``` awk -F: '$1 ~ /^ro*t/ { print $1 } ' /etc/passwd root ``` ### Python code ``` import os import re #depond , if you need to many time search and compare using compile findaccount=re.compile(r'^ro*') #first step to open File with open('/etc/passwd' , 'r') as passfile: #second step to read each line and to do pattern match #if match show first field for line in passfile: result=findaccount.match(line) if result: print(line.split(':')[0] else: pass ``` --- # EXAMPLE 8 ## Awk Code ``` awk -F: '{sum[$7]++}END{for(i in sum)print sum[i],i}' /etc/passwd Result: 1 1 /bin/sync 2 /bin/bash 2 /sbin/nologin 26 /bin/false 17 /usr/sbin/nologin ``` ### Python code ``` import os #first step to open File with open('/etc/passwd' , 'r') as passfile: counter=Counter() for line in passfile: field=line.split(':')[6] #print(field) counter[field] += 1 #print(help(counter)) for item in counter: print('{0},{1}'.format(item,counter[item])) Result: /bin/false ,26 /usr/sbin/nologin ,17 /bin/sync ,1 /bin/bash ,2 /sbin/nologin ,2 , ``` # Example9 用於去抓出一個檔案比對出來的行及下一行然後直接放進一個List 中 ``` import os import re import itertools file='mobile-142.txt' def create_list_of_match(file,searchstr): alias_index=[] with open(file, 'r') as f : for line_index, line in enumerate(f): result=re.findall(searchstr,line) if result: #print(line_index) alias_index.append(line_index) return alias_index def seekfile(file,location): with open(file,'r') as f: for i, line in enumerate(f): if location==i: print(line) return line def seekfile_and_offset(file,location,offset): with open(file,'r') as f: #current=f.readlines()[location] #nextone=f.readlines()[location+offset] content_list=[] location2=location+offset for i, line in enumerate(f): if location==i: content_list.append(line.strip()) elif location2==i: content_list.append(line.strip()) return content_list list=create_list_of_match(file,'alias') for x in list: print(seekfile_and_offset(file,x,1)) ``` # Example10 Usage : if and else 查出一個PATTERN 然後作比較 ``` awk -F: '/^root/{if($3==1){print "OK" } else {print "error"} } ' /etc/passwd error ``` Example 11 找出不固定位置的特定字元 ``` awk '/cs1/ {for(i=1;i<=NF;i++) { if ($i~/^cs1/ ) { print $i } } }' ./ns.log.0 ``` ![](/assets/Selection_110.png)
{"metaMigratedAt":"2023-06-15T04:32:52.530Z","metaMigratedFrom":"Content","title":"AWK and Python CODE 對比","breaks":true,"contributors":"[{\"id\":\"a42c0e9e-57e1-447c-bd6c-fb741876eeff\",\"add\":5619,\"del\":4}]"}
Expand menu