PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How do I count the number of lines in a bash variable, respecting emptiness?

 October 28, 2022     bash, is-empty, line-count, string     No comments   

Issue

We know how to count the number of lines in a variable. However, as noted in comments and answers there, the semantics are quirky when it comes to empty variables, as an empty variable is usually counted the same as a non-empty, no-newline variable:

$ echo -n "" | wc -l
0
$ echo -n "foo" | wc -l
0
$ echo "" | wc -l
1
$ echo "foo" | wc -l
1

not so good, if you want to count the number of results some other command returned.

Now, a partial workaround is suggested in one of the answers to that question:

printf "%s" "$a" | grep -c "^"

but that's not exactly what I'm after either, since it counts a non-empty variable whose value is a newline as having 0 lines.

My question: Other than counting "regularly" and then explicitly checking for the case of emptiness, is there a decent way to obtain such a count in bash?


Solution

awk to the rescue:

$ echo -n "foo" | awk 'END {print NR}'
1
$ echo -n "" | awk 'END {print NR}'
0


Answered By - Jé Queue
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing