获取包含特定字符串的列

get columns contain specific string

我有一个文件如下:

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

我想获取所有与字符串匹配的列 "a"。

a1    a2
a1
a1    a2    a3

我正在尝试使用awk,但只得到最后一个,而不是全部。

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

我建议你阅读 Reading and Writing Files from Python doc.And 有一个 try.Open 文件,并使用 for 循环获取每一行的内容作为一个字符串。

然后split the string and filter列表得到你想要的字段,如果你想要一个字符串,使用join

with open("tryme.txt") as f:
    for line in f:
        #split the string and filter it.

尝试自己编写代码,如果遇到困难,请询问 it.Whosebug 不是设计、编码或教程服务。

使用

输入

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

输出

$ 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

说明

awk '{                                        # call awk
        s="";                                 # set var s with null value, in fact it reset variable s for each line/record/row read by awk 
        for(i=1;i<=NF;i++)                    # NF gives no of fields in record, so loop through first to last field of current record/line/row
                if($i~/^a/)s=(s?s OFS:"") $i; # if current field($i) starts with a then, if variable s has something before then concatenate s with output separator and current field value, else set s with current field


        if(s)                                 # if s has something then  
            print s                           # print s
      }
     ' file

阅读更多关于 ternary operator

s = ( s ? s OFS : "" ) $i;

      ^
  Above one is same as below

# Or if(s != "") or if(length(s))
if(s)
{
    s = s OFS $i
}else
{
    s = $i
}

@hope:也试试看:

awk '{gsub(/[^a[0-9]]*/," ");gsub(/^[[:space:]]+|[[:space:]]+$/,"");print}'   Input_file

说明:除了其中没有字符串的字段外,全局替换所有内容。因为你没有提到是否有混合字段(也可能有 a 和其他东西)所以不考虑那部分,如果混合值(字符串 a 和其他)它只会打印 a's。 然后将 space 从行开始并以 space 结束替换为行中的 NULL,然后打印该行。

awk '{j=0;for(i=1;i<=NF;i++)if($i~/^a/){printf (++j<2?"":FS) $i};print""}' urfile

get columns contain specific string的正确方法是:

$ awk '{
    c=0
    for (i=1;i<=NF;i++) {
        if ( index($i,"a") ) {
            printf "%s%s", (c++ ? OFS : ""), $i
        }
    }
    if (c) {
        print ""
    }
}' file
a1 a2
a1
a1 a2 a3

这将适用于出现在任何字段的任何位置的任何字符串 "a",当目标字符串包含正则表达式元字符时不会产生错误匹配,并且当没有匹配时不会打印空行。