Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output all column numbers for a particular character

I have a matrix(about 10,000×10,000), and I want to find the column number that contains ‘0’.

Matrix (test.txt) :

1 1 1 1 1 1 1 1 1 1
1 0 1 1 1 0 1 1 1 1
1 1 1 0 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
3 2 2 3 3 0 3 2 2 2
3 2 1 3 3 0 3 2 2 0
3 2 2 3 3 2 3 2 2 2
1 1 1 1 1 1 1 1 1 1

Output (example) :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2 4 6 10

I am new to LINUX SHELL, and have not found much in similar examples. Any help would be much appreciated!!

I just know how to find the row number using grep -nw '0' test.txt|cut -f1 -d':', Maybe I can transpose the matrix first(like this)? And then use the code above, right? Is there an easier way to do it?

>Solution :

$ awk '
    /(^| )0( |$)/ {
        for ( i=1; i<=NF; i++ ) {
            if ( ($i == 0) && !seen[i]++ ) {
                cols[++numCols] = i
            }
        }
    }
    END {
        for ( c=1; c<=numCols; c++ ) {
            printf "%s%s", cols[c], (c<numCols ? OFS : ORS)
        }
    }
' file
2 6 4 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading