例子:
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