在没有wc的情况下计算Bash中的单词和字符

时间:2015-10-13 08:40:39

标签: bash

我有一个像这样的变量集:

CardView

我需要计算有多少单词和字符,而不使用其他程序,如wc。

我知道计算单词可以这样做:

sentence="a very long sentence with multiple       spaces"

但我如何计算包括空格在内的字符?

3 个答案:

答案 0 :(得分:5)

  

但我如何计算包括空格在内的字符?

计算字符串使用的长度:

echo "${#sentence}"
47

答案 1 :(得分:0)

您还可以将select customerId, case when HasA+HasB+HasC = 3 then 'A' when HasA+HasB = 2 then 'A' when HasB+HasC = 2 then 'B' when HasA+HasC = 2 then 'A' when HasA is null and HasB is null and HasC is not null then 'C' when HasB is null and HasC is null and HasA is not null then 'A' when HasC is null and HasA is null and HasB is not null then 'B' end as overallStatus from ( select customerId, max(case when Status = 'A' then 1 end) HasA, max(case when Status = 'B' then 1 end) HasB, max(case when Status = 'C' then 1 end) HasC from tableName group by customerId ) as t; 与正则表达式匹配:

    <RESULTS>
<DEVICE name="qwewewew">
<PORT name="ilo">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>ilo</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="onboard-1">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>net</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="abncd">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE/>
<CONNECTS/>
</PORT>
<PORT name="abncd">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>fiber</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
<PORT name="power">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE/>
<CONNECTS/>
</PORT>
<PORT name="serial">
<DB_SOURCE>abncd</DB_SOURCE>
<WIRE_TYPE>serial</WIRE_TYPE>
<CONNECTS>abncd</CONNECTS>
</PORT>
</DEVICE>
</RESULTS>

答案 2 :(得分:0)

在一行上使用awk

echo this string | awk '{print length}'

将stdin文本传递给awk的另一种方式:

awk '{print length}' <<< "this string"