2012-02-29 138 views
1

我试图找出模式的出现的次数与下面的代码文件:的Linux Shell脚本非法数字

#!/bin/sh 

var='grep -c 'abc' file1' 

if [ "$var" -lt 10 ]; then 
    echo "less than 10" 
fi 

我收到错误:非法数字:grep的-c ABC文件1

有人可以请帮忙。

谢谢。

回答

3

使用反引号(`)而不是单引号('):

#!/bin/sh 

var=`grep -c 'abc' file1` 

if [ "$var" -lt 10 ]; then 
    echo "less than 10" 
fi 
1

你可能想反引号(`)而不是单引号(')。即:

var=`grep -c 'abc' file1` 
1

你已经使用了单引号,而不是反引号让你var变量实际上是设置为一个字符串字面而不是该命令的结果。你会发现,如果你第一次呼应变量:

pax$ var='grep -c 'abc' file1' 
pax$ echo "[$var]" 
[grep -c abc file1] 

倒引号的版本是:

var=`grep -c 'abc' file1` 

,但我想用bash在可能的脚本建议。你会很难找到一个默认没有的主流发行版,有些人认为它比其他发行版更强大。实际上,在一些系统上,/bin/shbash

如果你可以去那鲁特的$()结构通常是一个好主意,因为你可以嵌套它们无痛苦:

var=$(grep -c 'abc' file1) 
0

尝试发布以下内容,以获得更好的答案:

  • grep --version
  • bash --version如果你的shell是Bash或让我们知道你正在使用哪个shell。
  • 在back-ticks中使用grep或如下所示
  • [[在Bash中比[更通用。

最后,我的机器上的以下作品没有任何错误:

#!/bin/bash 
var=$(grep -c "abc" file1) 
if [[ "$var" -lt 10 ]] 
then 
    echo "less than 10" 
fi 

执行:

[email protected]:~$ cat file1 
abc 
abcd 
abcde 
abcdef 
[email protected]:~$ 
[email protected]:~$ ./t.sh 
less than 10 
[email protected]:~$