从钥匙串输出中删除字符串

Removing string from keychain output

运行

之后

test=$(security 2>&1 >/dev/null find-generic-password -ga test) echo $test

输出是

password: "1234"

我想删除所有内容,只留下实际密码,在这种情况下只是

1234

有什么帮助吗?

如果格式始终是 password: "value",您可以 高效地 执行此操作,而无需任何外部实用程序,仅使用子字符串扩展:

echo "${test:11:-1}" #output: 1234

如果您坚持使用其他实用程序:

awk -F'"' '{ print  }' <<< "$test" #output: 1234
cut -d'"' -f2 <<< "$test" #output: 1234

如果您的密码中有 " 个字符,上述两个命令都会失败。另一个使用 sed 的解决方案与密码中的 " 配合使用:

sed 's/^password: "\(.*\)"$//' <<< "$test" #output: 1234

您可以通过以下方式解决:

命令:

 echo 'password: "1234"' | awk -F"\"" '{print }'

输出:

1234

在 Grep 中使用 Perl 兼容的正则表达式

如果您的系统有使用 PCRE 引擎编译的 grep(例如 pcregrep,或支持 grep -P),那么您可以将 pcregrep -o ': "\K[^"]+' 放入您的管道中。例如,仅将引号之间的 material 发送到标准输出:

$ echo 'password: "1234"' | pcregrep -o ': "\K[^"]+'
1234

$ echo 'password: "ABCD"' | pcregrep -o ': "\K[^"]+'
ABCD

$ echo 'password: "1A2B3C4D"' | pcregrep -o ': "\K[^"]+'
1A2B3C4D