What is the equivalent of Python dictionaries but in Bash (should work across OS X and Linux).
相关问题
- JQ: Select when attribute value exists in a bash a
- Move character on map on clicked position
- bash print whole line after splitting line with if
- “command not found” errors in expect script execut
- grep using grep results
相关文章
- Check if directory exists on remote machine with s
- Reverse four length of letters with sed in unix
- Creating a dictionary for each word in a file and
- Launch interactive SSH bash session from PHP
- BASH: Basic if then and variable assignment
- Bash script that creates a directory structure
- Test if File/Dir exists over SSH/Sudo in Python/Ba
- Can a VBScript function return a dictionary?
I agree with @lhunath and others that the associative array are the way to go with Bash 4. If you are stuck to Bash 3 (OSX, old distros that you cannot update) you can use also expr, which should be everywhere, a string and regular expressions. I like it especially when the dictionary is not too big.
Write your map as a string (note the separator ',' also at beginning and end)
Use a regex to extract the values
Split the string to list the items
Now you can use it:
Bash 3 solution:
In reading some of the answers I put together a quick little function I would like to contribute back that might help others.
A coworker just mentioned this thread. I've independently implemented hash tables within bash, and it's not dependent on version 4. From a blog post of mine in March 2010 (before some of the answers here...) entitled Hash tables in bash:
Sure, it makes an external call for cksum and is therefore somewhat slowed, but the implementation is very clean and usable. It's not bidirectional, and the built-in way is a lot better, but neither should really be used anyway. Bash is for quick one-offs, and such things should quite rarely involve complexity that might require hashes, except perhaps in your .bashrc and friends.
I create HashMaps in bash 3 using dynamic variables. I explained how that works in my answer to: Associative arrays in Shell scripts
Also you can take a look in shell_map, which is a HashMap implementation made in bash 3.
This is what I was looking for here:
This did not work for me with bash 4.1.5:
Just use the file system
The file system is a tree structure that can be used as a hash map. Your hash table will be a temporary directory, your keys will be filenames, and your values will be file contents. The advantage is that it can handle huge hashmaps, and doesn't require a specific shell.
Hashtable creation
hashtable=$(mktemp -d)
Add an element
echo $value > $hashtable/$key
Read an element
value=$(< $hashtable/$key)
Performance
Of course, its slow, but not that slow. I tested it on my machine, with an SSD and btrfs, and it does around 3000 element read/write per second.