看板 Linux 關於我們 聯絡資訊
Hi~ 各位板大先進大家好 小弟對於shell script 不是很熟悉 最近剛好碰到一個問題是 想要用shell script parse 字串 "asdfwer [ 1234, 3456 ]" 中的 1234 和 3456 出來 並且加以比對看數字是不是一樣 當然希望最好是一行 command就可以解決...|||Orz 不知道各位大大們對於這個問題有沒有什麼建議或是指教的 非常謝謝大家!!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.105.206
bitlife:grep -o '[0-9]*' 10/17 10:28
ptthidebear:感謝大大~ 不過出來的結果是空的 XDa" 10/17 10:34
bitlife:你要把你的文字內容當成上一行的輸入,不論是pipe或是直接 10/17 10:47
bitlife:加檔案名稱在命令的最後面 10/17 10:48
bitlife:上面的命令是只抓出數字,如果你還要進一步比對,要再多做一 10/17 10:49
bitlife:事. 不過因為對你的資料來源內容一無所悉,所以也無法給你 10/17 10:50
bitlife:明確命令,不過原則是用 bash read 和 test 來做. 10/17 10:51
ptthidebear:我是用cat test.txt | grep -o '[0-9]*' 10/17 10:54
ptthidebear:test.txt內容就是原文裡面的例子 10/17 10:54
OpenSolaris:ㄧ定要ㄧ行嗎?搞成一行串在一起的都很難想,不直觀. 10/17 10:58
ptthidebear:想請教大大如果不是一行的話...有什麼其他想法嗎@@? 10/17 11:10
ptthidebear:因為有特殊需求所以儘量得在一行完成...Orz 10/17 11:12
bitlife:我試了你的資料,會產生出兩列數字,你沒產生嗎? 10/17 11:48
bitlife:如果一定要一行完成,最好的方法是寫個C程式 10/17 11:48
ptthidebear:cat test.txt | grep -o '[0-9]*' 出來結果是空的 10/17 12:34
bitlife:這就腫了,難不成我們的 grep 版本產很多? 10/17 12:36
bitlife:差很多 10/17 12:37
bitlife:你man grep看看有沒有 -o 的說明? 10/17 12:37
ptthidebear:有呀~我剛剛跑不出來就man了一下 -o, --only-matching 10/17 14:18
ptthidebear:grep (GNU grep) 2.5.1 10/17 14:19
kdjf:test.txt裡面檢查一下東西還在嗎? 10/17 16:00
ptthidebear:都還在@@" 我剛剛試另一個test file 內容只有數字 10/17 16:06
ptthidebear:12345 然後 cat test2.txt | grep -o '[0-9]*'有出現 10/17 16:07
ptthidebear:12345沒錯... 10/17 16:07
[root@Acer xxx]# cat test1.txt asdfwer [ 1234, 3456 ] [root@Acer xxx]# cat test1.txt |grep -o "[0-9]*" [root@Acer xxx]# cat test1.txt |grep -o "[ [0-9]*, [0-9]* ]" [ 1234, 3456 ] [root@Acer xxx]# cat test2.txt 12345 [root@Acer xxx]# cat test2.txt |grep -o "[0-9]*" 12345 [root@Acer xxx]# 以上是我測試的結果...會不會pattern不match的關係@@? ※ 編輯: ptthidebear 來自: 140.123.105.206 (10/17 16:12)
bitlife:我的 grep 是 GNU grep 2.5.4, 莫非是版本問題? 10/17 16:30
bitlife:建議先更新 grep 版本,你的執行結果看起來像是 bug. 10/17 17:34
ptthidebear:可能沒辦法耶,因為就是要在這個平台上跑... 10/17 19:04
ptthidebear:我沒辦法控制這些版本Orz 10/17 19:04
Holocaust123:那就把grep裝在家目錄然後修改path讓該grep在前面吧 10/17 21:01
bitlife:我是覺得寫個C程式最快.一般熟C程度寫好應該不用10分鐘. 10/17 21:15
ptthidebear:謝謝各位,我想另外寫個小程式解決它了~:) 10/17 23:30
qsort:why not python? 10/18 02:01
OpenSolaris:Why not tcl? 10/18 09:16
kira925:Perl is your friend 10/18 09:59
bitlife:還有php也可以用.XD 就看原po熟哪種就是了. C是最快,原po 10/18 10:03
bitlife:有速度考量的話,用C最好. 10/18 10:03
ptthidebear:我是想用C,不過可能會跨平台,所以應該會用python 10/18 10:24