如何在文件中查找字符串并将下一个单词作为输入?

时间:2017-03-15 13:37:27

标签: linux bash shell terminal

我有一个配置文件,其结构如下:

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

3 个答案:

答案 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)

grepcut

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}"