1

I have data in 1 file

example:

a1b1:online                                                                        
xxxx:offline                                                              
wxyz:enable                                                      
a2b2:online                                           
txtx:disable                              

for single data, not an issue , but how about the double information for online?

how I can display information like

data a1b1 a2b2 are online    --- how to get this                          
data xxxx  are offline    -- no issue                                      
data wxyz are enable      -- no issue                                           

2 Answers 2

1
$ awk -F: 'a[$2] {a[$2] = a[$2]" "$1; next};
           {a[$2]=$1};

           END {for (s in a) { print "data " a[s] " are " s }}' input.txt 
data xxxx are offline
data txtx are disable
data a1b1 a2b2 are online
data wxyz are enable

This uses an associative array a (with the status, $2, as the key) to store the hosts ($1) which have that status. If the array element for a given status already exists, then append a space, and the hostname to it. Otherwise just create that element with that hostname.

(i'm assuming they are hostnames - doesn't matter. the code works on the data not on the definition)

When the entire input file has been read, it prints out the arrray in the desired format.

Note that because associative arrays in awk are not stored in any particular order, the output is unordered. If you need it sorted, you could do that in the awk script, but it's easier just to pipe the output into sort.

If you're only interested in the online status, you could pipe the output to grep, or do it in the awk script. e.g.

$ awk -F: '!/online/ {next};
           a[$2] {a[$2] = a[$2]" "$1; next};
           {a[$2]=$1};

           END {for (s in a) { print "data " a[s] " are " s }}' input.txt 
data a1b1 a2b2 are online
1
  • 1
    BTW, this algorithm could be implemented in any language that has associative arrays (aka "hashes") - including bash itself (but note that bash is much slower and less efficient than languages like awk or perl - or almost any other language - for text processing jobs like this...you CAN do things like this in bash, but that doesn't mean you WANT to, or SHOULD :-).
    – cas
    Commented Aug 1, 2019 at 3:11
0

command

for i in `awk -F ":" '{print $NF}' filename | sed '/^$/d'| awk '{if(!seen[$NF]++)print }'`; do  awk -v i="$i" -F ":" '$NF == i{print $1}' filename |sed "N;s/\n/ /g"| awk -v i="$i" '{print "data" " " $0" " "are "i}'; done

output

data a1b1 a2b2 are online
data xxxx are offline
data wxyz are enable
data txtx are disable

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.