hope hope - 9 months ago 35
Python Question

get columns contain specific string

I have a file that like follows:

cat text.txt
a1 a2 j
h a1
k p a1 a2 a3


And I want to get the columns than all match with a string "a".

a1 a2
a1
a1 a2 a3


I'm try used awk, but only get the last, not all.

awk '{for(i=1;i<=NF;i++){if($i~/^a/){arr=$i}} print arr}' text.txt
a2
a1
a3

Answer Source

Using

Input

$ cat file
a1       a2       j
h       a1
k       p       a1       a2      a3

Output

$ awk '{s="";for(i=1;i<=NF;i++)if($i~/^a/)s=(s?s OFS:"") $i; if(s)print s}' file
a1 a2
a1
a1 a2 a3