【问题标题】:comparing lines with awk vs while read line比较行与 awk 与同时读取行
【发布时间】:2013-04-24 15:30:29
【问题描述】:

我有两个文件,一个有 17k 行,另一个有 4k 行。我想将位置 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

【问题讨论】:

  • 使用 awk 您可以使用 NR 作为行号。这样您可能会节省时间。

标签: sed awk ksh cat


【解决方案1】:

这是怎么回事:

FNR==NR {                      # FNR == NR is only true in the first file

    s = substr($0,115,10)      # Store the section of the line interested in 
    sub(/^\s*/,"",s)           # Remove any leading whitespace
    sub(/\s*$/,"",s)           # Remove any trailing whitespace

    lines[s]=$0                # Create array of lines
    next                       # Get next line in first file
}
{                              # Now in second file
    for(i in lines)            # For each line in the array
        if (i~$0) {            # If matches the current line in second file 
            print lines[i]     # Print the matching line from file1
            next               # Get next line in second file
        }
}

将其保存到脚本 script.awk 并运行如下:

$ awk -f script.awk "$filename" "${file_dir}/id.txt" > "${dest_dir}/id.txt"

这仍然会很慢,因为对于第二个文件中的每一行,您需要查看第一个 中约 50% 的唯一行(假设大多数行确实匹配)。如果您可以确认第二个文件中的行与子字符串完全匹配,则可以显着改善这一点。


对于全行匹配,这应该更快:

FNR==NR {                      # FNR == NR is only true in the first file

    s = substr($0,115,10)      # Store the section of the line interested in 
    sub(/^\s*/,"",s)           # Remove any leading whitespace
    sub(/\s*$/,"",s)           # Remove any trailing whitespace

    lines[s]=$0                # Create array of lines
    next                       # Get next line in first file
}
($0 in lines) {                  # Now in second file
    print lines[$0]     # Print the matching line from file1
}

【讨论】:

  • 我可以确认第二个文件中的行与第一个文件中的子字符串完全匹配。
  • @user37774 我添加了一个脚本,对于全行匹配应该更快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
相关资源
最近更新 更多