[h1]COMMAND LINE PROGRAMS IN PYTHON:[h1]
This page has pograms which you can use as command line tools.
[h2]1) arrlen.py:[h2]
This program is used to print the length of each line in a file.
*CODE:*
from sys import stdin
standardin = stdin.readlines()
#print standardin
for i in range (0,len(standardin)) :
count =0
for j in standardin[i]:
if j not in "\n\r": count += 1
print str(count)+" " +standardin[i].replace("\n","").replace("\r","")
USE : echo test.txt | python arrlen.py
OUTPUT:
5 hello
6 there,
7 namaste
[h2]2) cat.py [h2]
This is used to print the the content of a file
*CODE:*
import sys
filenames= sys.argv[1:]
#print filenames
all_lines = []
for i in range (0,len(filenames)):
f = open(filenames[i], "r")
all_lines.extend(f.readlines())
f.close()
for i in all_lines:
print i.rstrip()
USE:python cat.py test.txt
OUTPUT:
hello
there,
namaste
[h2]3) stcount.py [h2]
This program is used count the frequency of a particular word in a string or file.
*CODE*
from sys import stdin
import sys
standardin = stdin.readlines()
all_lines = ''
for i in standardin:
all_lines += i.replace('\n','').replace('\r','')
word= sys.argv[1:][0]
n =len(all_lines.split(word))-1
print n
USE : echo "hello\nworld" | python stcount.py e
"e" is the word you want to count here
*OR*
echo test.txt | python stcount.py e
OUTPUT :
1
[h2]4) sort.py [h2]
This program is used to sort according to the length of a string
*CODE*
from sys import stdin
standardin = stdin.readlines()
parts=[]
for i in standardin:
i = i.replace("\n","").replace("\r","")
parts.append ( (int(i.split(" ")[0]), i ) )
parts = sorted(parts)
#print parts
for i in parts:
print i[1]
USE: cat test.txt | python arrlen.py | sort.py
OUTPUT:
11 hello world
12 this is test
17 how are you doing
[ul]
[li] powered by pavwiki [li]
[li] license: creative commons cc0 1.0 (public domain) [li]
[li] http://creativecommons.org/publicdomain/zero/1.0/ [li]
[ul]