Last active
March 8, 2025 20:36
-
-
Save mattmc3/1db531a59e107e619361d3f0e46f72c6 to your computer and use it in GitHub Desktop.
awk - Colorize any path in command output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/awk -f | |
# colorize-path - add color to paths in specified field | |
# usage: | |
# command | ./bin/colorize-paths | |
# git ls-tree -r HEAD | ./bin/colorize-paths -v field=4 | |
# ls -la | ./bin/colorize-paths -v field=9 | |
# | |
BEGIN { | |
RED="\033[31m" | |
BLUE="\033[34m" | |
RESET="\033[0m" | |
if (!field) field = 1 # default to field 1 if not specified | |
} | |
{ | |
# Store all fields before our target field | |
prefix = "" | |
for (i = 1; i < field; i++) { | |
prefix = prefix $i (i < field-1 ? OFS : "") | |
} | |
# Concatenate target field and all remaining fields | |
path = "" | |
for (i = field; i <= NF; i++) { | |
path = path $i (i < NF ? OFS : "") | |
} | |
# Match directories and files using split | |
n = split(path, parts, "/") | |
if (n > 1) { | |
# Reconstruct the directory part | |
dir = "" | |
for (i = 1; i < n; i++) { | |
dir = dir parts[i] "/" | |
} | |
path = BLUE dir RESET RED parts[n] RESET | |
} else { | |
path = RED path RESET | |
} | |
# Print the prefix and colorized path | |
if (prefix) | |
print prefix, path | |
else | |
print path | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment