• grep 无法搜索shell 传递过来的变量?


    起因的需求是 需求是 要找出a文件中id 对应在b文件中的信息,不难,循环a文件中的id,在b文件中进行grep,输出匹配上的上就还可以了

    如下图两个文件

     

    $ cat a.txt
    id
    abc
    def
    GHT
    
    $ cat b.txt
    abc     12      hgy
    def     13      hl
    123     14      hl2
    GHT     11      hgy3
    
    

    写个脚本

    $ cat t3.sh
    #!/bin/bash
    cat a.txt | while read line ;
    do
            echo ${line}
            grep ${line} b.txt
            sleep 2
    done
    

    ###返回结果纳闷 居然没有匹配上,可我们肉眼都能看出来能匹配的上

    $ bash t3.sh
    abc
    def
    GHT
    

    上传到服务器还是如此,

    ###于是使用 -x 参数 调试一下脚本

    $ bash -x t3.sh
    + cat a.txt
    + read line
    + echo $'abc
    '
    abc
    + grep $'abc
    ' b.txt
    + sleep 2
    + read line
    + echo $'def
    '
    def
    + grep $'def
    ' b.txt
    + sleep 2
    + read line
    + echo $'GHT
    '
    GHT
    + grep $'GHT
    ' b.txt
    + sleep 2
    + read line
    

    ###居然有 ,难怪找不到,grep 的变量已经变了 grep 'abc' 变成grep 'abc '百度了解到是换行符问题 源文件a中,明明只有abc,def,GHT ,结尾并没有带上r,我们用***cat -A filename *命令查看文件中所有不可见的字符 ref:https://zhang.ge/488.html Linux终端:用cat命令查看不可见字符

    $ cat -A a.txt
    abc^M$
    def^M$
    GHT^M$
    

    发现每行多了个^M$ ,原因何在,主要是windows 中编写的txt 文件在linux中打开时,格式发生了转变 实验对比一下,在Linux中vim 手工编辑一个test.txt ,cat -A 查看一下

    DELL-PC@DESKTOP-KD5L8P2 MINGW64 ~/Desktop/test
    $ cat -A test.txt
    bc$
    11$
    123$
    asdf$
    mn$
    

    结论

    结尾只有一个$,我们知道linux 中$是一行的结束标识符,而我们的a.txt 是在windows 中编辑的,结尾^M$ 比Linux中结尾$多了符号^M 所以grep 无法查到,造成grep无法查找shell传过来的变量的假象。

    ###修改脚本

    #!/bin/bash
    cat -A a.txt | while read line ;
    do
            id = `echo $line | cut -d"^" -f1`
            grep $id b.txt
            sleep 2
    done
    
    #结果
    $ bash -x t1.sh
    + cat -A a.txt
    + read line
    ++ echo 'abc^M$'
    ++ cut '-d^' -f1
    + id=abc
    + grep abc b.txt
    abc     12      hgy
    + sleep 2
    + read line
    ++ echo 'def^M$'
    ++ cut '-d^' -f1
    + id=def
    + grep def b.txt
    def     13      hl
    + sleep 2
    + read line
    ++ echo 'GHT^M$'
    ++ cut '-d^' -f1
    + id=GHT
    + grep GHT b.txt
    GHT     11      hgy3
    + sleep 2
    + read line
    

     

  • 相关阅读:
    Arc Catalog重建索引时报错:ORA02298: 无法验证 (SDE.A18_FK1) 未找到父项关键字 (A18_FK1)
    网站复杂信息自动录入处理
    httpModules remove does not work in a folder or virtual directory
    事件触发型ActiveX放置在网页中的部分思考
    Javascript中文字符串处理额外注意事项
    指定web.config让httphandler处理某目录及子目录下所有文件
    windows命令行里取得年月日时分秒的办法
    手工删除打印任务
    数据绑定表达与javascript字符串连用
    【kserve】kserve安装记录
  • 原文地址:https://www.cnblogs.com/yellow-hgy/p/10780578.html
Copyright © 2020-2023  润新知