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\r' abc + grep $'abc\r' b.txt + sleep 2 + read line + echo $'def\r' def + grep $'def\r' b.txt + sleep 2 + read line + echo $'GHT\r' GHT + grep $'GHT\r' b.txt + sleep 2 + read line 

###居然有\r ,难怪找不到,grep 的变量已经变了 grep 'abc' 变成grep 'abc\r'百度了解到是换行符问题 源文件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 

 

猜你喜欢

转载自www.cnblogs.com/yellow-hgy/p/10780578.html