This tutorial will be all about writing a simple grep clone in arc.
When completed our grep clone will be able to:
- Accept a
PATTERNto search for
- Accept any number of
- Ouptut lines of the
FILESthat match the
PATTERNto stdout, with coloring
To begin with we need to scaffold the project
Install arc if you haven't already
And create a file called
grep_clone.py that contains the following:
Next, we're going to want to add arguments to the command. For now, we'll only be implementing the
FILES arguments. All of grep's many flags will be left alone for now.
As you can see, we've already got a validated regex pattern, and file handles to each of the specified files.
With type handling / data validation already out of the way, the implentation will be fairly straightfoward.
import re import arc from arc import color from arc.types import File @arc.command() def grep(pattern: re.Pattern, files: list[File.Read]): for file in files: # Iterate over all the files for line in file.readlines(): # Iterate over all the line in the file if match := pattern.search(line): # check for a match # If there is a match, highlight it colored = pattern.sub( color.fg.RED + match.group() + color.effects.CLEAR, line, ) print(colored, end="") grep()