Skip to content

Commit 3a31fbf

Browse files
added python the code for the cat command
1 parent e328bd5 commit 3a31fbf

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

  • implement-shell-tools/cat

‎implement-shell-tools/cat/cat.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import glob
2+
import argparse
3+
4+
def cat(filepath, n=False, b=False, line_counter=None):
5+
try:
6+
with open(filepath) as f:
7+
for line in f:
8+
if b:
9+
if line.strip():
10+
print(f"{line_counter[0]:6}\t{line}", end='')
11+
line_counter[0] += 1
12+
else:
13+
print(line, end='')
14+
elif n:
15+
print(f"{line_counter[0]:6}\t{line}", end='')
16+
line_counter[0] += 1
17+
else:
18+
print(line, end='')
19+
except FileNotFoundError:
20+
print(f"cat: {filepath}: No such file or directory")
21+
22+
def main():
23+
parser = argparse.ArgumentParser(description = "Concatenate files and print on the standard output.")
24+
parser.add_argument('-n', action='store_true', help='number all output lines')
25+
parser.add_argument('-b', action='store_true', help='number non-empty output lines')
26+
parser.add_argument('files', nargs='+', help='files to concatenate')
27+
args = parser.parse_args()
28+
29+
files = []
30+
for pattern in args.files:
31+
files.extend(glob.glob(pattern) or [pattern])
32+
33+
line_counter = [1]
34+
for file in sorted(files):
35+
cat(file, args.n, args.b, line_counter)
36+
37+
if __name__ == "__main__":
38+
main()

0 commit comments

Comments
 (0)