我有一个配置文件,其结构如下:
username abc123
licensekey qwer1234
该文件位于$HOME/.test.config
。
现在,我想搜索关键字licensekey
,并希望将以下单词qwer1234
复制为我的密钥。如果没有单词许可证密钥或文件不存在,我希望用户手动添加许可证密钥并打开文件。
你有什么建议吗?到目前为止,我的代码中是否犯了一些错误?
到目前为止我的代码是:
keyfile='$HOME/.test.config'
if grep -q licensekey "$keyfile"; then
#what now?
else
while true; do
read -p "Whats your License Key? " key
key >> ${keyfile}
break
done
fi
答案 0 :(得分:1)
您可以使用awk
匹配文件中的字符串并提取密钥
示例强>
$ cat file
username abc123
licensekey qwer1234
$ awk '$1 == "licensekey"{print $2}' file
qwer1234
要从用户那里读取key
(如果不在文件中),我们可以编写类似
key=$(awk '$1 == "licensekey"{print $2}' file)
if [[ -z $key ]]
then
read -p "Whats your License Key? " key
echo "licensekey $key" >> file
fi
# Do something with the kye
答案 1 :(得分:0)
grep
和cut
:
grep licensekey config_file | cut -d' ' -f2
答案 2 :(得分:0)
您还可以使用sed
来解析许可证密钥:
#/usr/bin/env bash
set -o nounset # error if variable not set
set -o errexit # exit if error
# Using double quote let bash expand the variable
# Local limit the scope of the variable
local keyfile="${HOME}/.test.config"
#gets the first valid key
local key=$(sed -n 's/licensekey[[:space:]]//p')
#Append the key to file if not existing
if [ -z "${key}" ]; then
read -r -p "Whats your License Key? " key
echo "licensekey ${key}" >> ${keyfile}
fi
echo "License key is: ${key}"