包含在文件
问题描述:
的整数行数我试过,但它不工作:包含在文件
count1=0;
count2=0;
for n in $*
do
for(i=1;i<='wc -l <$n';i++) do
if [[ $i == *"[0-9]* ]]; then
count1=count1+1;
else
count2=count2+1;
fi
done
done
COUNT1是包含整数和COUNT2为不包含整数行线。
输入:
yes 145 10
no no
10 20
输出:
count1=2, count2=1
答
使用grep -c
来算匹配正则表达式的所有行数。使用-v
选项来计算不匹配的行。
count1=$(grep -c "[0-9]" "[email protected]")
count2=$(grep -v -c "[0-9]" "[email protected]")
答
for n in $*
要遍历所有的位置参数,使用"[email protected]"
(含引号)代替$*
。前者实际上与包含空格的参数一起工作(参见the manual)。
for(i=1;i<='wc -l <$n';i++) do
这应该是for ((i=1;i <= $(wc -l < $n); i++)) ; do
(manual)。就像现在这是一个语法错误。即使如此,它仍然只会循环播放数字,而不会读取任何内容。有关如何读取文件,请参阅BashFAQ。
if [[ $i == *"[0-9]* ]]; then
这是否可以,除了那里的唯一的报价。
count1=count1+1;
这将字符串count1+1
赋给变量count1
。你可能想在这里使用一个Arithmetic expansion:count1=$((count1 + 1))
wc -l Barmar
''*'[0-9] *' – Barmar
'count1 = count1 + 1'不应该在'bash'中增加一个变量的正确方法。 – Barmar