Results 1 to 10 of 10
I need help to write a simple bash script. In a directory, there are 6 log files. Each file has a name and date, for example file1.Sep0918, file2.Sep0918, etc. For ...
- 09-19-2008 #1Just Joined!
- Join Date
- Sep 2008
- Posts
- 3
Help with Bash Script Please!!
I need help to write a simple bash script. In a directory, there are 6 log files. Each file has a name and date, for example file1.Sep0918, file2.Sep0918, etc. For each file, I have to search for a key word, lets say the word "Error". I need to count the occurances of that word in each file and print them out in to file. The directory path should be an argument past to the script. The file output file should cut out the date from the filename and should resemble something like:
54 errors in file1
12 errors in file2
.
.
.
- 09-19-2008 #2
This sounds suspiciously like a homework assignment, which are not allowed per The Forum Rules.
I suggest that you read a few guides on Bash scripting:
Bash Guide for Beginners
Advanced Bash-Scripting GuideDISTRO=Arch
Registered Linux User #388732
- 09-19-2008 #3Just Joined!
- Join Date
- Sep 2008
- Posts
- 3
This is actually not a homework assignment. I am a beginner program and am trying to learn scripting. I would appreciate any help. I did not ask for exact code, even a description would be helpful.
Thanks
- 09-19-2008 #4Linux User
- Join Date
- Aug 2006
- Posts
- 458
to search for one file
i leave it to you to search the restCode:egrep -o Error file | wc -l
- 09-19-2008 #5Just Joined!
- Join Date
- Sep 2008
- Posts
- 3
If i pass the script an argument thats the directory path, how do I get it to read each file on the path? Thats my biggest issue. There are several files in the directory, so to read each one, I thought using a for loop would work. So far, i've thought of...
for file in $1
do
<parse each file>
done
but all that does is make $file store the directory path.
- 09-19-2008 #6Linux Guru
- Join Date
- Nov 2007
- Location
- Córdoba (Spain)
- Posts
- 1,513
You'd rather do
Provided that $1 will hold the path.Code:for file in "$1"/*
If you need to process subdirs as well, you can do a recursive script, but I advise to use the command find instead. Read on the -exec option for find.
For more versatility, you could use this as well:
Code:find /path/to/ -type f | while read file do #whatever done
- 09-20-2008 #7Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
or
Code:for file in $(find /path/to -type f) do # whatever done
- 09-20-2008 #8Linux User
- Join Date
- Aug 2006
- Posts
- 458
- 09-22-2008 #9
That method can work with a tiny modification:
This will tell the loop to only split on newlines, preventing spaces from messing with things. IFS stands for "Internal Field Separator".Code:IFS=$'\012' for file in $(find /path/to -type f) do # whatever doneDISTRO=Arch
Registered Linux User #388732
- 09-22-2008 #10Linux User
- Join Date
- Aug 2006
- Posts
- 458


Reply With Quote
