Jump to content

Shell Scripting

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
9 replies to this topic

#1
Guest_NeedHelp_*

Guest_NeedHelp_*
  • Guests
I need to do an IF statement and if there is a count of two do one thing and a count of one do another. My question is, is there a count function? My function basically looks like this:

cat filename | grep ..... | {print 1}

If there are two results in I need the 2nd one, otherwise the first one. Any ideas?

#2
Guest_NeedHelp_*

Guest_NeedHelp_*
  • Guests
Bump, can anyone help?

#3
ghostdog74

ghostdog74

    Newbie

  • Members
  • Pip
  • 6 posts

NeedHelp said:

I need to do an IF statement and if there is a count of two do one thing and a count of one do another. My question is, is there a count function? My function basically looks like this:

cat filename | grep ..... | {print 1}

If there are two results in I need the 2nd one, otherwise the first one. Any ideas?

if i understand you, you wanted to count a word occurence in a file?

awk -v RS="gggg" 'END{print (NR?NR-1:0)}' file #gggg is the search string



#4
Guest_Jordan_*

Guest_Jordan_*
  • Guests
You can also use grep for that or WC. Are you counting lines or characters?

grep -c // Line count
wc -l // Line Count

So just do a normal shell if statement on a variable that contains those values.

#5
ghostdog74

ghostdog74

    Newbie

  • Members
  • Pip
  • 6 posts

Jordan said:

You can also use grep for that or WC. Are you counting lines or characters?


grep -c // Line count

wc -l // Line Count


So just do a normal shell if statement on a variable that contains those values.

depending on OP's requirement, if he is counting words, grep -c would not be accurate if 2 or more words occur on a line. grep -c will count as 1, because it returns matching number of lines which the word is found.also wc -l counts number of lines, not words.

#6
Guest_Jordan_*

Guest_Jordan_*
  • Guests
grep -c will only count lines, hence the "// Line Count" comment.You can change the -l of wc to "wc -w" for word count.

#7
ghostdog74

ghostdog74

    Newbie

  • Members
  • Pip
  • 6 posts
wc -w counts total words in a file. it will not work if OP only wants to count a certain word in a file.

#8
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Sorry, I meant to type -m

-m, --chars print the character counts

#9
ghostdog74

ghostdog74

    Newbie

  • Members
  • Pip
  • 6 posts
for example this sample file:

# more file

this is a test line

this is second line

# wc -m file

40 file

# wc -c file

40 file

but if OP wants to count how many times the word "line" occurs, both the above will not work, whether -m or -c. however:

# awk -v RS="line" 'END{print (NR?NR-1:0)}' file

2



#10
Guest_NeedHelp_*

Guest_NeedHelp_*
  • Guests
I needed the line count. I was able to accomplish it doing:

COUNT=`cat $1 | grep -c  rtn`

if [ "$COUNT" -eq 1 ]; then
.....