Reputation: 3974
When I am giving the following command -
ip -br -c addr show | awk '{print $2}'
It returns something like this output -
UNKNOWN
UP
DOWN
UP
UP
UP
UP
but when I want to only print the ones which are UP and I say -
ip -br -c addr show | awk '$2 == "UP"'
it does not return anything.
I have used awk with such comparisons and it works, here I am wondering may be -br
does not return a comparable string. Or is there something I am doing wrong.
Upvotes: 2
Views: 437
Reputation: 163517
The command prints the colors as well, you can see the non printing characters using:
ip -br -c addr show | cat -v
If you want to keep the color, another option could be using index()
to check for UP
ip -br -c addr show | awk 'index($2, "UP")'
Upvotes: 2
Reputation: 627292
This is because you tell ip
command to add color codes to your output by using the -c
option:
-c[color][={always|auto|never}
Configure color output.
Remove -c
, and ip -br addr show | awk '$2 == "UP"'
will work.
Or, you may match the green color code:
ip -br -c addr show | awk '$2 == "\033[32mUP"'
Upvotes: 1
Reputation: 133700
With your shown samples, please try following GNU grep
code.
ip -br -c addr show | grep -oP '^\S+[^A-Z]+UP\D+.*?\K(\d+\.){3}\d+'
Explanation: Simple explanation would be, running ip -br -c addr show
command and sending its output as standard input to grep
command. In GNU grep
code using oP
options to print only matched values and enable PCRE regex engine. In main program mentioning regex(whose explanation is added below) and printing only matched part.
Explanation of regex:
^\S+[^A-Z]+UP\D+.*? ##Matching non-spaces from starting of line followed by non-alphabets followed by UP followed by NON-DIGITS(1 or more occurrences) followed by a lazy match of next pattern.
\K ##\K will forget the previous matched value and will print only further mentioned regex value.
(\d+\.){3}\d+ ##Matching digits(1 or more occurrences) followed by a dot and matching this group 3 times followed by 1 or more occurrences of digits.
Upvotes: 2