I've got a file that contains a list of key=value
pairs, each on its own line. What's the best way to fetch the value for a specified key using shell commands?
我有一个包含key = value对列表的文件,每个文件都有自己的行。使用shell命令获取指定键值的最佳方法是什么?
3 个解决方案
#1
6
what about
关于什么
grep "key" my_file | cut -d'=' -f2
#2
1
This is how I do it in ksh.
这就是我在ksh中的表现。
FOO=$(grep "^key=" $filename | awk -F"=" '{print $2}')
You can also use cut instead of awk. If you delimit the key pair with a space you can drop the -F"=".
你也可以使用cut而不是awk。如果使用空格分隔密钥对,则可以删除-F“=”。
#3
1
read -r -p "Enter key to fetch: " key
awk -vk="$key" -F"=" '$1~k{ print "value for "k" is "$2} ' file
output
产量
$ ./shell.sh
Enter key to fetch: key1
value for key1 is value1
or you can just use the shell(eg bash)
或者你可以只使用shell(例如bash)
read -r -p "Enter key to fetch: " key
while IFS="=" read -r k v
do
case "$k" in
*"$key"* ) echo "value of key: $k is $v";;
esac
done <"file"
#1
6
what about
关于什么
grep "key" my_file | cut -d'=' -f2
#2
1
This is how I do it in ksh.
这就是我在ksh中的表现。
FOO=$(grep "^key=" $filename | awk -F"=" '{print $2}')
You can also use cut instead of awk. If you delimit the key pair with a space you can drop the -F"=".
你也可以使用cut而不是awk。如果使用空格分隔密钥对,则可以删除-F“=”。
#3
1
read -r -p "Enter key to fetch: " key
awk -vk="$key" -F"=" '$1~k{ print "value for "k" is "$2} ' file
output
产量
$ ./shell.sh
Enter key to fetch: key1
value for key1 is value1
or you can just use the shell(eg bash)
或者你可以只使用shell(例如bash)
read -r -p "Enter key to fetch: " key
while IFS="=" read -r k v
do
case "$k" in
*"$key"* ) echo "value of key: $k is $v";;
esac
done <"file"