6

我需要计算给定变量的行数。例如,我需要找到有多少行VAR,在哪里VAR=$(git log -n 10 --format="%s")

我试过 with echo "$VAR" | wc -l),确实有效,但如果VAR为空,则为 prints 1,这是错误的。有解决方法吗?比使用if子句检查变量是否为空更好...(也许添加一行并从返回值中减去 1?)。

4

4 回答 4

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
于 2014-05-19T11:41:29.673 回答
6

你总是可以有条件地写它:

[ -n "$VAR" ] && echo "$VAR" | wc -l || echo 0

这将检查是否$VAR有内容并采取相应措施。

于 2014-05-19T11:36:14.560 回答
5

对于纯 bash 解决方案:不要将git命令的输出放入变量(可以说是丑陋的),而是将其放入数组中,每个字段一行:

mapfile -t ary < <(git log -n 10 --format="%s")

然后你只需要计算数组中的字段数ary

echo "${#ary[@]}"

如果您需要检索第 5 条提交消息,此设计还将使您的生活更简单:

echo "${ary[4]}"
于 2014-05-19T12:53:03.997 回答
2

尝试:

echo "$VAR" | grep ^ | wc -l
于 2014-05-19T11:44:31.660 回答