Skip to content
Advertisement

How to apply regex to specific column in awk

la() {
     ls -lhAXF "$@" | awk '
     BEGIN {
         FPAT = "([[:space:]]*[^[:space:]]+)";
     } {
         $1 = "33[1m" "33[31m" $1 "33[0m";
         $2 = "33[1m" "33[32m" $2 "33[0m";
         $3 = "33[1m" "33[33m" $3 "33[0m";
         $4 = "33[34m" $4 "33[0m";
         $5 = "33[1m" "33[35m" $5 "33[0m";
         $6 = "33[1m" "33[36m" $6 "33[0m";
         $7 = "33[1m" "33[37m" $7 "33[0m";
         $8 = "33[1m" "33[33m" $8 "33[0m";
         print
     }'
}

This will colorize the output of ls -lhAXF How to apply the color to specific type of item using regex, for example i want the folder to be green, the .config folder red, the regular file blue or something like that.

folder – match $9 column containing ‘/’ in the end of word hidden folder – match $9 column containing ‘.’ in the start of word regular file – the rest of unmatched in column $9

how to apply regex to specific column like that in awk? I’m using Debian 11

Advertisement

Answer

how to apply regex to specific column like that in awk?

Syntax for that in GNU AWK is as follows

$1~/pattern/

where 1 is number of column. Consider following simple example, let file.txt

1. ABC
2. 123
3. DEF

then

awk '{print $2~/^[0-9]*$/}' file.txt

output

0
1
0

Explanation: This does check if 2nd column ($2) content consist solely of digits. ^ denotes begin of field and $ denotes end of field.

(tested in GNU Awk 5.0.1)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement