Awk脚本开发求助:实现两文件日期列的匹配校验及指定格式结果输出
解决方案:对比两个CSV文件的日期列并输出详细结果
Hey there! Let's get this date comparison working properly for you. Your original awk script had a couple of key issues—first, you used tabs (\t) as the field separator but your files are comma-separated, and the logic wasn't structured to generate the detailed match/mismatch output you need.
正确的Awk脚本
Here's a script that will do exactly what you want:
awk -F',' 'NR==FNR {date[$1] = $2; next} { if (date[$1] == $2) { printf "%s 两个文件中的日期匹配 %s\n", $1, $2 } else { printf "%s 文件中存在日期不匹配,文件1中为%s,文件2中为%s\n", $1, date[$1], $2 } }' FILE1 FILE2
脚本解释
Let's break down what each part does:
-F',': Sets the field separator to a comma, which matches your file format (each line has two columns separated by a comma).NR==FNR {date[$1] = $2; next}: This block runs only when processing the first input file (FILE1). It stores the date value (second column) in an array calleddate, using the first column value as the key. Thenextcommand skips to the next line so we don't run the rest of the script forFILE1.- The remaining block runs for the second file (
FILE2):- We check if the date from
FILE1(stored indate[$1]) matches the date from the current line inFILE2($2). - If they match, we print your desired success message with the column1 value and matching date.
- If they don't match, we print the mismatch message showing both dates from each file.
- We check if the date from
示例运行结果
Using your sample FILE1 and FILE2 content, running this script will output:
tbla 两个文件中的日期匹配 2020-07-01 tblb 文件中存在日期不匹配,文件1中为2020-08-12,文件2中为2020-08-11 tblc 文件中存在日期不匹配,文件1中为2019-01-01,文件2中为2019-01-02 tbld 两个文件中的日期匹配 2016-02-27
为什么原脚本没工作
Your original script had two main problems:
- You used
-F'\t'(tab separator) but your files use commas—so awk couldn't split the columns correctly. - The logic counted duplicate
$1$2combinations, which only tells you which lines are identical across both files. It couldn't generate the detailed mismatch messages you need, or reference the date from the first file when processing the second.
内容的提问来源于stack exchange,提问作者Suraj
相关产品推荐
相关产品推荐

