我需要计算给定变量的行数。例如,我需要找到VAR
有多少行,VAR=$(git log -n 10 --format="%s")
。
我尝试了echo "$VAR" | wc -l)
,这确实有效,但如果VAR
为空,则打印1
,这是错误的。这有解决方法吗?比使用if
子句检查变量是否为空更好...(可能添加一行并从返回的值中减去1)。
答案 0 :(得分:13)
wc
计算换行符数。您可以使用grep -c '^'
来计算行数。
您可以看到与以下区别:
#!/bin/bash
count_it() {
echo "Variablie contains $2: ==>$1<=="
echo -n 'grep:'; echo -n "$1" | grep -c '^'
echo -n 'wc :'; echo -n "$1" | wc -l
echo
}
VAR=''
count_it "$VAR" "empty variable"
VAR='one line'
count_it "$VAR" "one line without \n at the end"
VAR='line1
'
count_it "$VAR" "one line with \n at the end"
VAR='line1
line2'
count_it "$VAR" "two lines without \n at the end"
VAR='line1
line2
'
count_it "$VAR" "two lines with \n at the end"
产生什么:
Variablie contains empty variable: ==><==
grep:0
wc : 0
Variablie contains one line without \n at the end: ==>one line<==
grep:1
wc : 0
Variablie contains one line with \n at the end: ==>line1
<==
grep:1
wc : 1
Variablie contains two lines without \n at the end: ==>line1
line2<==
grep:2
wc : 1
Variablie contains two lines with \n at the end: ==>line1
line2
<==
grep:2
wc : 2
答案 1 :(得分:6)
你总是可以有条件地写下来:
[ -n "$VAR" ] && echo "$VAR" | wc -l || echo 0
这将检查$VAR
是否包含内容并采取相应行动。
答案 2 :(得分:5)
对于纯粹的bash解决方案:不是将git
命令的输出放入变量(可以说是丑陋的),而是将它放在一个数组中,每个字段一行:
mapfile -t ary < <(git log -n 10 --format="%s")
然后您只需要计算数组ary
中的字段数:
echo "${#ary[@]}"
如果您需要检索第5条提交消息,此设计也会让您的生活变得更简单:
echo "${ary[4]}"
答案 3 :(得分:2)
尝试:
echo "$VAR" | grep ^ | wc -l