Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to find the number of certain types of files that have a '_' in the filename.

I'm a massive beginner so my syntax looks like this at the moment;

foreach txt ( 'ls *.txt')
set n=0
if(grep _ txt) then
@ n = n+1
endif
end

It doesn't work as my if statement isn't correct, but I'm not sure how to define saying if the txt file has a '_' within the filename then increment n by 1.

share|improve this question
    
Are you trying to count the number of files that have a _ in them, or for each file, how many _ it has? –  Mat Feb 25 '12 at 13:06
    
The actual name of the file not what's within the file –  r0bb077 Feb 25 '12 at 13:22
    
So you want the number of files that have at least one _, or the number of _ in each filename? –  Mat Feb 25 '12 at 13:28
    
The number of files that have a '_' within the filename, thanks! –  r0bb077 Feb 25 '12 at 13:59

3 Answers 3

up vote 1 down vote accepted

One way of doing it would be to use the shell's globbing capabilities rather than using grep.

set n=0
foreach txt (*_*.txt)
    @ n++
end

The syntax for the "if grep" thing if you needed that for other reasons would be:

if ( { grep -q _ $var } ) then
  ...
endif

(-q tells grep to be quiet and not print out anything.)

share|improve this answer
    
Hi Matt, the first one of this is just what I was looking for. i find it hard to find any of this online, do you have a good resource place where I can read up on what you've just done for me? –  r0bb077 Feb 25 '12 at 17:06
    
For a start, just read through your shell's man page (skip the sections that you really don't care about), that will make you familiar with all the stuff it can do. Then it's more of a matter of trying things out and looking at existing scripts (your system is full of them, just poke around). (And I wouldn't try to learn csh/tcsh if you're just starting. ksh/bash are much more common these days, you'll find more things about them online.) –  Mat Feb 25 '12 at 17:13

To get the number of filenames that have a certain character use:

set n=`ls *.txt | fgrep -c _`

This will print only the filenames that have the character found and then count the number of entries returned. In tcsh, you need to prefix assignments with set.

share|improve this answer

You can use the find command in combination with wc to get the number of file with a _ in the name:

set n=`find [path] -maxdepth 1 -name "*_*.txt" | wc -l`

Replace [path] with the directory you would like to search.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.