Bash是這種大小的關聯數組的錯誤工具。考慮使用的語言更適合(Perl,Python和Ruby的,PHP,JS,等等等等)
對於一個只有猛砸環境你可以使用它通常與猛砸安裝sqlite3
SQL數據庫。 (但它不是POSIX)
首先,您將從您的csv文件創建數據庫。有很多方法可以做到這一點(Perl,Python和Ruby的,GUI工具),但是這是很簡單的在sqlite3的command line shell(exp.db
不能在這一點上存在)交互做:
$ sqlite3 exp.db
SQLite version 3.19.3 2017-06-27 16:48:08
Enter ".help" for usage hints.
sqlite> create table mapping (id integer primary key, n integer);
sqlite> .separator ","
sqlite> .import /tmp/mapping.csv mapping
sqlite> .quit
或者,管的SQL語句:
#!/bin/bash
cd /tmp
[[ -f exp.db ]] && rm exp.db # must be a new db as written
echo 'create table mapping (id integer primary key, n integer);
.separator ","
.import mapping.csv mapping' | sqlite3 exp.db
(注:如寫的,exp.db
必須不存在,或者你會得到INSERT failed: UNIQUE constraint failed: mapping.id
你可以寫這樣的數據庫exp.db
被更新,而不是通過CSV文件創建的,但你可能會想。使用像Python,Perl,Tcl,Ruby等語言來做到這一點。)
無論哪種情況,這將創建一個將第一列映射到第二列的索引數據庫。進口將需要一段時間(15-20秒與198 MB的例子),但它創建從導入CSV新的持久性數據庫:
$ ls -l exp.db
-rw-r--r-- 1 dawg wheel 158105600 Nov 19 07:16 exp.db
然後你就可以快速地從猛砸查詢該新的數據庫:
$ time sqlite3 exp.db 'select n from mapping where id=1350044575'
1347465036
real 0m0.004s
user 0m0.001s
sys 0m0.001s
我的舊iMac需要4毫秒。
如果你想使用bash的變量爲您查詢,您可以連接或根據需要建立查詢字串:
$ q=1350044575
$ sqlite3 exp.db 'select n from mapping where id='"$q"
1347465036
而且由於分貝是持久性的,你可以比較csv文件的文件倍該數據庫文件來測試是否需要重新創建:
if [[ ! -f "$db_file" || "$csv_file" -nt "$db_file" ]]; then
[[ -f "$db_file" ]] && rm "$db_file"
echo "creating $db_file"
# create the db as above...
else
echo "reusing $db_file"
fi
# query the db...
更多:
- sqlite tutorial
- sqlite home
Bash是不是非常適合此類任務。使用適當的編程語言會更好。 – janos
你的問題是根本:你選擇了錯誤的工具... – HuStmpHrrr
'sqlite3'或'mysql'更適合。 – dawg