Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash, compare the output of a command

I am trying to do something like this:

  if [ $(wc -l $f) -lt 2 ]

where $f is a file. When I run this, I get the error message:

  [: too many arguments

Does anybody know how to fix this line in my command?

The full script is:

for f in *.csv
do
  if [ $(wc -l $f) -lt 2 ]
      then
      echo $f
      fi
done
like image 605
user788171 Avatar asked Mar 12 '13 13:03

user788171


People also ask

What is Echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

How do you compare in bash?

Comparison Operators When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.


2 Answers

at least in my case wc -l filename does output 32 filename being 32 the number of lines. so you must strip of the filename after the line count. You could change your code from

if [ $(wc -l $f) -lt 2 ]

to

if [ $(wc -l $f | cut -f1 -d' ') -lt 2 ]

or

if [ $(wc -l < $f) -lt 2 ]

If does not solve your problem please add the output of wc -l filename to your question or as a comment.

like image 200
dwalter Avatar answered Sep 21 '22 15:09

dwalter


Try this :

  if (( $(wc -l < "$f") < 2 ))

or if you want to keep your syntax :

  if [ $(wc -l < "$f") -lt 2 ]

Note

((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression

like image 20
Gilles Quenot Avatar answered Sep 24 '22 15:09

Gilles Quenot