1列に複数の文字列を処理する方法

1列に複数の文字列を処理する方法

彼の形式に似たカンマ区切りのファイルがあります。

aa.com,1.21.3.4,string1 string2 K=12     K2=23  K3=45 K4=56
bb.com,5.6.7.8,string1 string2 K=66     K2=77  K3=88 K4=99

スペースで区切られた文字列を含む3番目の列を取得したいと思います。 3番目の列の最初の2つの文字列をカンマで区切り、3番目の列の残りの文字列を無視するようにファイルを処理したいと思います。最初の 2 つのフィールドにはスペースは含まれません。 3番目の列の文字列の数がすべてのレコードに対して固定されているわけではありません。この例では、5つのスペースで区切られた6つの文字列です。しかし、それはある程度かもしれません。

必要なのは、3番目の列の最初の2つの文字列を取得し、コンマで区切って3番目の列の文字列の残りの部分を無視することです。

aa.com,1.21.3.4,string1,string2
bb.com,5.6.7.8,string1,string2

ベストアンサー1

努力する:

awk '{print $1, $2}' OFS=, infile
aa.com,1.21.3.4,string1,string2
bb.com,5.6.7.8,string1,string2

この場合、最初または2番目のフィールドにスペースがある場合は、次のようにします。

awk -F, '{ match($3, /[^ ]* +[^ ]*/); 
           bkup=substr($3, RSTART, RLENGTH);
           gsub(/ +/, ",", bkup); # replace spaces with comma
           print $1, $2, bkup
}' OFS=, infile

説明する:読む男性awk:

match(s, r [, a])  
          Return the position in s where the regular expression r occurs, 
          or 0 if r is not present, and set the values of RSTART and RLENGTH. (...)

substr(s, i [, n])
          Return the at most n-character substring of s starting at I.
          If n is omitted, use the rest of s.

RSTART
          The index of the first character matched by match(); 0 if no
          match.  (This implies that character indices start at one.)

RLENGTH
          The length of the string matched by match(); -1 if no match.

おすすめ記事