![如何计算引号内的字符数?](https://linux22.com/image/1160088/%E5%A6%82%E4%BD%95%E8%AE%A1%E7%AE%97%E5%BC%95%E5%8F%B7%E5%86%85%E7%9A%84%E5%AD%97%E7%AC%A6%E6%95%B0%EF%BC%9F.png)
例子:
Known Data: Total population = "150"
问题:使用 bash 如何找出引号内的字符数?并将该输出分配给变量?
答案1
使用 grep:
var=$(grep -Po '(?<=").*(?=")' fileName | tr -d '\n' | wc -c)
对于您的示例返回:
echo $var
3
使用 sed:
var=$(sed -r 's/^.*"(.*)".*/\1/' fileName | tr -d '\n' | wc -c)
答案2
使用 awk:
string='Known Data: Total population = "150"'
var=$(awk -F\" '{print length($2)}' <<< "$string")
答案3
正如您在中提到的bash
,假设有一次发生"string"
,您可以执行以下操作:
str='Known Data: Total population = "150"'
strip=${str/\"*\"/}
len=$(( ${#str} - ${#strip} -2 ))
然后:
echo $len
3
答案4
使用perl
:
每行一个/第一个匹配项:
perl -ne '{ print; m/"(.*?)"/; print length($1),"\n"; }'
每行多个匹配项:
perl -ne '{ print; while (m/"(.*?)"/g) { print length($1),"\n"; } }'
你的例子:
echo 'Known Data: Total population = "150"' | \
perl -ne '{ print; m/"(.*?)"/; print length($1),"\n"; }'
Known Data: Total population = "150"
3
包含 2 个引号字符串的示例:
echo 'Known Data: Total population = "150"
Two quoted strings: "70" and "6000"' | \
perl -ne '{ print; while (m/"(.*?)"/g) { print length($1),"\n"; } }'
Known Data: Total population = "150"
3
Two quoted strings: "70" and "6000"
2
4
print;
如果不需要打印原始行,请省略。
例如:
var=$(echo 'Known Data: Total population = "150"' | \
perl -ne '{ m/"(.*?)"/; print length($1),"\n"; }')
echo $var
3