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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM