如何比较shell脚本中的两个文件? [英] How to compare two files in shell script?

查看:64
本文介绍了如何比较shell脚本中的两个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的场景.我有两个文件,每条记录的 3-25 个字符是一个标识符.基于此,我需要比较它们,如果标识符匹配,则用新文件数据更新旧文件.标识符以 01 开头.请看下面的脚本.这给出了一些错误,如我无法理解的第 12 行预期的参数.

Here is my scenario. I have two files which are having records with each record's 3-25 characters is an identifier. Based on this I need to compare both of them and update the old file with the new file data if their identifiers match. Identifiers start with 01. Please look at the script below. This is giving some error as "argument expected at line 12 which I am not able to understand.

#!/bin/ksh
while read line
  do
    c=`echo $line|grep '^01' `
    if [ $c -ne NULL ];
      then
        var=`echo $line|cut -c 3-25`
    fi
    while read i
      do
        d=`echo $i|grep '^01' `
        if [ $d -ne NULL ];
          then
            var1=`echo $i|cut -c 3-25`
            if [ $var -eq $var1 ];
              then
                $line=$i
            fi
        fi
      done < test_monday
  done < test_sunday

请帮我提前谢谢

推荐答案

除非您在 Bash 和 ksh 中编写可移植到原始 Bourne shell 或其他不支持该功能的脚本 你应该对字符串和文件使用[[形式的测试.

Unless you are writing a script for portability to the original Bourne shell or others that do not support the feature, in Bash and ksh you should use the [[ form of test for strings and files.

减少了对引用和转义、模式和正则表达式匹配等附加条件的需求,以及使用 &&|| 而不是-a-o.

There is a reduced need for quoting and escaping, additional conditions such as pattern and regular expression matching and the ability to use && and || instead of -a and -o.

if [[ $var == $var1 ]]

此外,NULL"在 Bash 和 ksh 中并不是一个特殊值,因此您的测试总是会成功,因为 $d 是针对文字字符串NULL"进行测试的.

Also, "NULL" is not a special value in Bash and ksh and so your test will always succeed since $d is tested against the literal string "NULL".

if [[ $d != "" ]]

if [[ $d ]]

对于数值(不包括前导零,除非您使用八进制),您可以使用数值表达式.在这种情况下,您可以省略变量的美元符号.

For numeric values (not including leading zeros unless you're using octal), you can use numeric expressions. You can omit the dollar sign for variables in this context.

numval=41
if ((++numval >= 42))  # increment then test
then
    echo "don't panic"
fi

没有必要对子字符串使用 echocut.在 Bash 和 ksh 中,您可以:

It's not necessary to use echo and cut for substrings. In Bash and ksh you can do:

var=${line:3:23}

注意:cut 使用字符位置作为范围的开始和结束,而这个 shell 构造使用起始位置和字符计数,因此您必须相应地调整数字.

Note: cut uses character positions for the beginning and end of a range, while this shell construct uses starting position and character count so you have to adjust the numbers accordingly.

避免使用反引号是个好主意.使用 $() 代替.这可以嵌套并减少或更容易引用和转义.

And it's a good idea to get away from using backticks. Use $() instead. This can be nested and quoting and escaping is reduced or easier.

这篇关于如何比较shell脚本中的两个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆