awkを使用して行を読み取るときの比較

awkを使用して行を読み取るときの比較

2つのファイルがあります。 1つは17kライン、もう1つは4kラインです。 2 番目のファイルの各行について、位置 115 と位置 125 を比較し、一致する場合は、最初のファイルの行全体を新しいファイルに書きたいと思います。私は解決策を見つけ、 'cat $filename | を使ってLINEを読みながらファイルを読みました。しかし、完了するのに約8分かかります。この処理時間を短縮するために「awk」を使用するなどの他の方法はありますか?

私のコード

cat $filename | while read LINE
do
  #read 115 to 125 and then remove trailing spaces and leading zeroes
  vid=`echo "$LINE" | cut -c 115-125 | sed 's,^ *,,; s, *$,,' | sed 's/^[0]*//'`
  exist=0
  #match vid with entire line in id.txt
  exist=`grep -x "$vid" $file_dir/id.txt | wc -l`
  if [[ $exist -gt 0 ]]; then
    echo "$LINE" >> $dest_dir/id.txt
  fi
done

ベストアンサー1

以下はうまくいき、スペースを削除するように更新されました。

#!/usr/bin/awk -f
# NR is the current line number (doesn't reset between files)
# FNR is the line number within the current file
# So NR == FNR  takes only the first file
NR == FNR {
    # Mark the current line as existing, via an associative array.
    found[$0]=1

    # Skip to the next line, so we don't go through the next block
    next
}
{
    # Take the columns we're looking for
    cols = substr($0,115,11)

    # Strip whitespace (space and tab) from the beginning (^) and end ($) 
    gsub(/^[ \t]+/,"", cols)
    gsub(/[ \t]+$/,"", cols)

    # Check the associative array to see if this was in the first file
    # If so, print the full line
    if(found[cols]) print;
}       

ファイルに入れて、次のいずれかのコマンドを使用して呼び出します。

awk -f script.awk patterns.txt full.txt
./script.awk patterns.txt full.txt

おすすめ記事