Home > Back-end >  How to apply regex to specific column in awk
How to apply regex to specific column in awk

Time:11-03

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

CodePudding user response:

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)

  • Related