- How to count using the grep command in Linux/Unix
- Grep counts the number of lines in the file that contain the specified content
- Grep counts the number of times of the specified content in a file
- Grep count the number of files in the directory whose filename contains the specified keyword
- Grep matches and reverses by line number
- grep two words on the same line
- Grep count the number of non-duplicate lines in a file
- Grep Count Lines If a String / Word Matches on Linux or Unix System
- Grep Count Lines If a String / Word Matches
- Summing up
- How to Count lines in a file in UNIX/Linux
- Using “wc -l”
- Using awk
- Using sed
- Using grep
- Some more commands
- How to count total number of word occurrences using grep on Linux or Unix
- Show the total number of times that the word foo appears in a file named bar.txt
- How To Use grep Command In Linux / UNIX With Practical Examples
- Did you know?
- grep command examples in Linux and Unix
- Syntax
- How do I use grep to search a file on Linux?
- How to use grep recursively
- How to use grep to search words only
- How to use grep to search 2 different words
- Ignore case
- How can I count line when words has been matched
- Force grep invert match
- Display lines before and after the match
- UNIX / Linux pipes
- How do I list just the names of matching files?
- Colors option
- Conclusion
How to count using the grep command in Linux/Unix
Linux grep command is one of the most commonly used command-line tools. We often use it to check the number of times of a words, phrases, strings in a text file or patterns to find the number of occurrences of files with specific names under folders.
Of course, you can also use a pipeline to do your daily work using a combination of grep and other commands. For example, use the grep command and the wc command to count the number of files that contain the specified content.
Suppose you have an test6.txt file containing the sentences:
Grep counts the number of lines in the file that contain the specified content
In the following example, we will use the grep command to count the number of lines in the file test6.txt that contain the string “dfff”
Using grep -c options alone will count the number of lines that contain the matching word instead of the number of total matches.
You can also use the grep command, pipe, and wc command to achieve the same effect as the grep-c option in the following example.
Grep counts the number of times of the specified content in a file
In the following example, we use grep -w to count the number of times of the string “dfff” in the file
Grep count the number of files in the directory whose filename contains the specified keyword
In the following example, the grep directory contains files whose filenames contain the keyword “test”, and we use the ls command, pipe, and wc command to count the number of files whose filenames contain the keyword “test” in the directory.
In the example above, we can count the number of lines or the total number of occurrences of a keyword in a file.
Sometimes, however, we also need to count the keyword to appear in the file, at the same time, according to the line number in reverse order.
Grep matches and reverses by line number
grep two words on the same line
Grep matches multiple keywords, which we often use on a daily basis. But matching multiple keywords has two meanings:
* Match file containing keyword1 and containing keyword2 … : AND
* Match file containing keyword1 or containing keyword2 … : OR
In the first example, we use the grep -e option to match the line containing the word “dfff” or “apple” in the file test6.txt.
In the second example, we used multiple grep commands and pipes to match lines containing both “dfff” and “apple” words in the file test6.txt.
Grep count the number of non-duplicate lines in a file
Use the grep command to count the number of the same lines in the file?
Источник
Grep Count Lines If a String / Word Matches on Linux or Unix System
Grep Count Lines If a String / Word Matches
The syntax is as follows on Linux or Unix-like systems:
grep -c ‘word-to-search’ fileNameHere
For example, search a word named ‘vivek’ in /etc/passwd and count line if a word matches:
$ grep -c vivek /etc/passwd
OR
$ grep -w -c vivek /etc/passwd
Sample outputs indicating that word ‘vivek’ found one times:
However, with the -v or —invert-match option it will count non-matching lines, enter:
$ grep -v -c vivek /etc/passwd
Sample outputs:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -c : Display only a count of selected lines per FILE
- -v : Select non-matching lines
- —invert-match : Same as above.
Using grep command to count how many times the word ‘vivek’ and ‘root’ found in /etc/passwd file on Linux or Unix.
Summing up
We can easily suppress normal grep or egrep command output bypassing the -c option. Instead, it will print a count of matching lines for each input file. I would urge you to read the grep command man page to get additional information by typing the following man command:
man grep
man egrep
grep —help
egrep —help
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Count lines in a file in UNIX/Linux
Question: I have a file on my Linux system having a lot of lines. How do I count the total number of lines in the file?
Using “wc -l”
There are several ways to count lines in a file. But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output.
So consider the file shown below:
1. The “wc -l” command when run on this file, outputs the line count along with the filename.
2. To omit the filename from the result, use:
3. You can always provide the command output to the wc command using pipe. For example:
You can have any command here instead of cat. Output from any command can be piped to wc command to count the lines in the output.
Using awk
If you must want to use awk to find the line count, use the below awk command:
Using sed
Use the below sed command syntax to find line count using GNU sed:
Using grep
Our good old friend «grep» can also be used to count the number of lines in a file. These examples are just to let you know that there are multiple ways to count the lines without using «wc -l». But if asked I will always use «wc -l» instead of these options as it is way too easy to remember.
With GNU grep, you can use the below grep syntax:
Here is another version of grep command to find line count.
Some more commands
Along with the above commands, its good to know some rarely used commands to find the line count in a file.
1. Use the nl command (line numbering filter) to get each line numbered. The syntax for the command is:
Not so direct way to get line count. But you can use awk or sed to get the count from last line. For example:
2. You can also use vi and vim with the command «:set number» to set the number on each line as shown below. If the file is very big, you can use «Shift+G» to go to the last line and get the line count.
3. Use the cat command with -n switch to get each line numbered. Again, here you can get the line count from the last line.
4. You can also use perl one lines to find line count:
Источник
How to count total number of word occurrences using grep on Linux or Unix
Show the total number of times that the word foo appears in a file named bar.txt
The syntax is:
grep -c string filename
grep -c foo bar.txt
Sample outputs:
To count total number of occurrences of word in a file named /etc/passwd root using grep, run:
grep -c root /etc/passwd
To verify that run:
grep —color root /etc/passwd
Pass the -w option to grep to select only an entire word or phrase that matches the specified pattern:
grep -w root /etc/passwd
OR
grep -c -w root /etc/passwd
In this example only match a word being with root:
grep —color -w ‘^root’ /etc/passwd
grep -c -w ‘^root’ /etc/passwd
To show only the matching part of the lines.
grep -o ‘root’ /etc/passwd
grep -c -o ‘root’ /etc/passwd
Sample session:
Fig.01: Counting occurrence of words/strings using grep command
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How To Use grep Command In Linux / UNIX With Practical Examples
Tutorial requirements | |||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Requirements | Linux/Unix/macOS | ||||||||||||||||||||||||||||||||||||||||||||||||||||
Root privileges | No | ||||||||||||||||||||||||||||||||||||||||||||||||||||
Difficulty | Easy | ||||||||||||||||||||||||||||||||||||||||||||||||||||
Est. reading time | 8 mintues | ||||||||||||||||||||||||||||||||||||||||||||||||||||
Options | Description |
---|---|
-i | Ignore case distinctions on Linux and Unix |
-w | Force PATTERN to match only whole words |
-v | Select non-matching lines |
-n | Print line number with output lines |
-h | Suppress the Unix file name prefix on output |
-r | Search directories recursivly on Linux |
-R | Just like -r but follow all symlinks |
-l | Print only names of FILEs with selected lines |
-c | Print only a count of selected lines per FILE |
—color | Display matched pattern in colors |
If you enjoyed the grep tutorial, then you might like to read our “Regular Expressions in Grep” tutorial. Read grep command man page by typing the following man command:
man grep
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I found this tutorial being the most clear and helpful one. Thank you.
for searching multiple string using GREP command, please use below commands
grep -ir ‘string1\|string2’
above command is not working, instead
grep -ir «string1\|string2» dir_name
hello sandeep ,
padhai karke aao and type your answer Here…….padhi nehi karna aata he to gharko ja kar to make cow shed
Are you serious? And you never made a mistake asking any question? People who put others down to make themselves look superior in intelligence are usually the ones suffering from intellect. People like you follow and can never think for themselves. And people like Jeyaram who possess the balls to ask a questionable question will be the self thinkers. And those self thinkers are the inventers behind what ever you’re memorizing to make yourself LOOK intelligent.
Intelligence or our position never said us to disrespect people.i agree with you mo and It is better to say a fool ,that he is a fool.while he was in a imagination that he is the great intelligent in the world.
whatever you all are thinking, i am the great intelligence in this universe, the only one, in the whole universe, and beyond them. . . cheers and applause!
I cannot say anything regarding when the comment was made in past, after all it is couple years ago.
However, both @Sandeep and @Jeyaram .
only difference is that @Sandeep ‘s code
is finding the matches in the current directory while @Jeyaram
specifies which directory he wants to search.
Find which option is more suits the needs.
I agree. One of the original blog for Linux. Thank you for all hard work.
This Tutorial is so far helpful to me.
what if i want to search keyword
like “$this->Products” or “[‘status’]” ?
Sir mai ye command chala nhi pa rha hu. Please suggest.
single quote ko bhi escape karo
this is very useful to me.. thanks …
Very helpful. saved my time.
What is the best way to grep recursively through a directory tree, and display the pattern matches, that occur in just all the *.cpp files?
grep -HRn “look for this” *.cpp
doesn’t work (on Linux)
grep -r –include=”*.cpp” ‘look for this’ .
(“.” is current directory)
find . -name “*.cc” |args grep -n “pattern”
small correction
find . -name “*.cc” |xargs grep -n “pattern”
what if i want to search like this
Hi
I want to search t1.spq, t2.spq ….. tn.spq words from a file
grep -i “*.spq” filename doesn’t work
Please tell how can search such words??
you can try out the below command..
grep -i ^t..spq filename
Best regards,
Mohanraj
avoid using * grep -i “spq” tt.sh
then you will get all the words which will have spq.
if some thing need to refrained from that need to get the desired out put then use
grep -i “spq” tt.sh | grep -v ” somepattern”
How can i grep for an output that come after a statement: eg Expires: 10/May/2009.
If i want to caputure only the date, how can i grep for what comes after the colon (:)
echo ‘Expires: 10/May/2009’ | cut -d: -f2
OR
echo ‘Expires: 10/May/2009′ | awk -F’:’ ‘< print $2>‘
This is quite informative…… Thanks.
Also I have a question, what is the expansion of ‘grep’? Can anyone answer?
globally search a regular expression and print
This helps a lot,,
Rizvana,
grep means Get Regular Expression and Print
How can i do calculation on dates;
eg to know the number of days between ‘todays date’ and a day like ’15/may/2009′
thanks .i gt the rite information.
Hi,
How can I use grep function to search files that file name with “ord” or “rec” from specific dir??
grep -ir “ord\|rec” filename
Hi
lets say i have some data :
a
a
a
b
b
b
c
c
c
can I use grep comand to make like this :
a
b
c
thanks
Try uniq command.
grep -ir “a\|b\|c” filename
Vivek,
its working…..thanks a lot
Hi,
No one know how to use grep function to search files that file name with “ord” or “rec” from specific dir??
Hi,
I’d like to get the total cpu and memory usage easily and I think of using ‘dstat’ command. Can I get the values corresponding to the free and used column with grep?
——memory-usage——
used buff cach free
153M 876k 24M 4392k
cheers!
The Most Helpful POST
For those who want to search files with wild cards and the like, try the find command with -exec. find /dir/to/search/ -iname *.cpp -exec grep ‘word’ ‘<>‘ \;
and snake, I do not think it is possible to search columns with grep, I’m 98% sure that it is line (row) only.
As i was i beginner , it helped me a lot . I would like to thank all the people who contributed it to the public … than you so much
whats the use of egrep and fgrep
give examples of both
egrep is for regex and fgrep is for fixed string. I will update FAQ with more examples.
this is the best and the most understandable tutorial i have seen till date.
GOOD WORK!!
This tutorial is very easy to follow and enabled me to learn so much within a very short time
hi this is really really helpful and very fast introduction for grep very nice
exact and accurate content with no irrelevent text..
clean and accurate .thanks
Can someone help me for a data like:
aa:abc
bb:def
cc:ghi
dd:ijk
aa:pqr
bb:stu
cc:vwx
dd:yza
Description of data:
aa, bb, cc, dd comprise one record. Blank line is dividing 100 of such records.
question1) How to grep “cc:” that is empty value? i am unable to do this because it gives all the values.
question2) I need to print value of “aa:…” for all the records whose “dd:uvw”. How to do this?
hi all..
can anyone please explain me about this command
ps -ef|grep -v grep|grep $orasid >>/dev/null
ok..i feel really dumb..but i got this task i have to do to find a hidden file or something like that and im pretty sure i would use the command ls or whatever.
my problem is i dont no what im doing at all here..were do i type the command in at? all these things jus teach u the commands. yea im dumb i dont have a clue were to type it in..
if someone could please help me out here it be much appreciated! thanx
You can get more information in here: linuxcommand.org
It is possible to get grep of some numbers which are there in a list
hii..
It goes something like this..
i want to list a oracle database instance (say orasid=tiger) using this command..
I issued each command in separate and could understand little bit..
1. ps -ef :: lists all running processes
2. the output is directed to “grep -v grep” now
3. what that command does is just filter out any text containing ‘grep’..
4. this output is now sent to “grep $orasid”
5. it will just fetch only those running process like ” tiger ”
6. the output is redirected to /dev/null where the output is just discarded..
after this command here they used
if[ $? -ne 0]
then ————–
else —————–
fi
where $? reads output of previous command…
here $? is 0 as the command hasn’t thrown any error
Dear All ,
Thnaks for this nice chart it helps me a lot .
1- If i need to search for a “word” inside a directory that holds files, these files are located in the “www”
2- Also to search for a “word” in the all the databases in : /var/lib/mysql/database
What is the grep command to find a string of charactes like below
I am just using KY as an example but I want the command to list any state abbreviations followed by a 9 digit zip code. Any help is appreciated
grep ^[a-z]*4$ filename
this is better way to represent.. i hope
please solve my query
my query is “how can i search the text in hole file of a particular dirctory”
Hi i wud like an explanation of the ff command
grep[a-g]…[r-z]text.txt
This Tutorial is very helpful to me.
** answer1 **
cat file | grep ‘^cc:$’
will produce only cc: with no value.
Learn regular expressions. In the command above regular expression is between ”. So… cat is normal command that prints file. Then result is piped (|) to grep, which processes it with regular expression (^cc:$).
This regex basically matches lines, which contain:
^ – beginning of the line
c – letter c
c – letter c
: – colon
$ – end of line
If there is something between colon (:) and end of line ($), in your case some value, then line is not produced by grep.
** answer2 **
How to check value of aa: in the record which contain dd:uvw?
cat file | grep -B3 ‘dd:uvw’
-B3 tells grep to show line that matches our pattern and 3 lines Before (you can change this number if you want, you can use -A4 to show 4 lines After).
So the command above will produce whole 4 line of each record, which contain dd:uvw. To show only lines with aa: and their values, we can simply add subsequent grep:
cat file | grep -B3 ‘dd:uvw’ | grep ‘aa’
…and that’s it.
@Sam
grep [a-g]…[r-z]text.txt
will match files which names start with a,b,c,d,e,f or g, then there are subsequent three characters – each dot (.) represent any character – then there is r,s,t,u,v,w,x,y or z and then text.txt.
So it can be:
bokkrtext.txt
aiiiztext.txt
and so on…
@ jyothi
ps -ef|grep -v grep|grep $orasid » /dev/null
Explanation:
ps -ef lists processes. On that list there is number of every process, even number of grep process executed in this line. For example if i try to grep non-existing process john by issuing command ps -ef | grep john, then i will get this:
dev 6271 5933 0 05:43 pts/0 00:00:00 grep john
Even if there is no process I am looking for, I will get result from grep. I don’t want that to happen, so I will have to grep invert match (grep -v pattern as explained in the howto above).
In other words ps -ef | grep -v grep will list processes excluding grep.
After next pipe you have:
grep $orasid
$string recalls value of variable defined before.
If you define $orasid=bob, then your command will be equal to:
ps -ef | grep -v grep | grep bob » /dev/null
If $orasid=william, then your command will be equal to:
ps -ef | grep -v grep | grep william » /dev/null
and so on…
» /dev/null redirects output of the command to nowhere, because we don’t want to see grep output on our screen, when executing the code.
Summarizing:
$orasid=tiger
.
ps -ef | grep -v grep | grep $orasid >> /dev/null
.
if [ $? -ne 0]
then echo ‘claws’
else echo ‘no claws’
fi
If there is process named tiger (output of grep is not empty), then we get claws, else we get no claws 🙂
How can i search users, who can sign in in the system, with the grep commando?
very useful to me..
i found this tutorial really helpful…
well i hv one doubt…
if i have two files, namely..
cat >file1
1
2
3
4
cat >file2
1
2
Now wat command and iptions to use if i want only 3 and 4 as output i.e.
only those lines which are not present in file2 wen compaed to file1… plz help….
diff file1 file2
Simply super . thanks
This is great article , i am using the windows Grep editor, I am search the text content \”*hello*\” to get the world hello in all the files. I didnt get any output . Could suggest me what i should use.
Reply to Shan
wel u can use
grep -iw hello filename
if two words ex. Hello and
Hi, use foll syntax
egrep -iw ‘hello|Hi filename
Please do explain, what do the values between colons represent? For example:
grep video /etc/groups
See /etc/group file format.
How to count total number of lines using shell script.
Hi
I have an outstanding issue with me…
i know the specific pattern in the file but dont know the name of the file/script and dont know the location either.
How to search the filename with simply the pattern in that file.
Actually at some xyz location a .dmp file gets created (xyz.dmp (everyday it creates the same file as it a daily backup.))…now i dont know which script creates this .dmp file…So i need to know the name of the script.
Well, I didn’t found an answer, maybe you can help me.
I look for something like:
grep “[string a] AND [string b]” (print all lines who include [string a] and [string b])
grep “[string a] OR [string b]” (print all lines who include [string a] or [string b])
grep “NOT [string a]” (print all lines except [string a])
In order to count “words” , “characters” and “lines” in a file there is a bash command called “wc”.
wc -l esakki Feb 11, 2010 @ 5:50
How can i found system ip with mac address using grep command, pls tell anyone.
how do u run a grep cmd to exclude multiple lines from a file and write remaining lines to a file?
this is tutorial is very helpful for me.
REALLY GREAT BLOG!!1
hi, I am trying to to something like this…
filename_$CLIENT_NUMBER_sapphire_$DATE.var
filename_0_sapphire_20102002.var
filename_1_sapphire_20102002.var
…
filename_22_sapphire_20102002.var
filename_23_sapphire_20102002.var
so i wanna get a list of all these vars that are set for a certain day for all the client_number(0 to 24)… in an ordered fashion.
set | grep 20102002 | grep filename_ — gives me the 0 file and then 10, 11… and then the 1, 2 (filename_0_sapphire_20102002.var)
i have tried sort and got no results. Please can u help.
did this too:
set | grep 20102002 | grep filename_ ‘5’ — and get only 0 to 9 vars… how do i get 0 to 23 in order.
really it is very help ful to me.
How you go about listing user and last day of access ?
Hey,
I have a question. I have two files and I want to compare the files in such a way that it takes the data that is in file 1 and searches in file 2 and returns me items it did not find. (file 2 has more/newer data). I tried this command but it doesn’t look like it is working.
grep -v -f Currentsttuf.txt newstuff.txt> difference.txt
Very clearly explained… thanks!
very good ………………
please send me useful shell programing in my mail..
vikas kumar
for f in ‘cat all_logs0708’;
do
echo $f
grep ‘ZYXzyx’ $f >> all_out
done
I’d like to have the $f value prefixed on each output line. Is this possible?
How to find the files accessed in last 3 days using a grep command.
what if i want to exclude a certain word, for instance ‘prism’
This what I have so far:
grep -i ‘ism$’ /usr/dict/words
i want it to list every word that ends in ‘ism’ but would like to exclude ‘prism’
i only want to use one grep.
you can grep -v “word which you want to exclude” filename
I have 2 files. File1 contains a list of long-strings with their corresponding informations. File2 contains portions of the strings (short-strings) found in file 1. I would like to find which “short-strings” within file2 is present in file1 and extract the corresponding information. The ideal output file should be short-strings + long-string + corresponding information. Please help… Thanks in advance
Hi xD
I have a problem with grep -v. I want to exclude a line and the 6 lines before it, so I tried
|grep -v -B6 ‘my text’ but that doesn’t work, only without the -B6.
But how else can i exclude the other lines in quite a simple way because i need this option many times :S ?
Please help me
I have a data like
:
** SPFS310 LED is on
LED is on: MB . See prtdiag -v and /var/adm/messages for more details.
cbm850=TCS-CBM2;NODE=TCS-CBM2-unit0;CLASS=HW;HWTYPE=SYSBOARD
Mon Aug 9 11:05:50 2010
* APCL303 Trouble condition asserted.
Communication with the Core is not established
cbm850=TCS-CBM2;NODE=TCS-CBM2-unit0;CLASS=APPL;APPLTYPE=SDM_BASE.logs:s
tart_sdmlaq
Tue Aug 10 04:38:30 2010
I want to display the paragraph which contains ** i.e my output should be
** SPFS310 LED is on
LED is on: MB . See prtdiag -v and /var/adm/messages for more details.
cbm850=TCS-CBM2;NODE=TCS-CBM2-unit0;CLASS=HW;HWTYPE=SYSBOARD
Mon Aug 9 11:05:50 2010
What command should I use.Can anyone please tell me.
How me difference between egrep and fgrep and how to use these commands
Try the below shell programs.
1. Locate build.number in the input file. Get the value and increment the value to next number for every run.
2. Have a some parm=value in input file. From shell read these and use it in the shell, pass it to another shell.
Take two file that have parm=value. From source file copy all the parms that exists in another file (target) with the values retrieved from the source file
I hope this doesn’t sound silly. How do I eliminate a directory from a grep search? Let’s say I want to look for the word “hamburger” that exists somewhere is a file in a subdirectory. I want to recursive search but I want to eliminate one of the subdirectories from being searched. To search I would normally do something like #grep -r hamburger /var/www/* But let’s suppose that /var/www/waterpipe is 2 TB in size and I don’t think hamburger is in there anywhere. How do I search everything else in /var/www/* but not /var/www/waterpipe? MANY thanks.
plz tel me the command to fetch a line from a file where the 5th col states a particular word like say “YES”
Hi Vivek,
I have a concerns how to use grep for the following
1. In a file of 100 lines how to get contents from line number 75 to 90?
2. Cut lines in a file with index numbers 6, 7, 10, 11
3. Print lines with index 70 to 95 from a file using head and tail.
Anticipating u r reply
Thanks a lot
3) head -90 filename | tail -25
grep “^t7.spq” filename
that was so helpful, I now understand how does grep command works. now what soes this rilly specify “ps -ef | grep”
Hi to all,
I just started to learn linux a month ago
Can I extract 2 to 6 letter words from a text file using one grep command only!
To mention that each word is on its own line
what’s the grep command to do this job?
I tried any combination of grep and not the result which I am looking for
someone reffred me the “man grep” command it rilly helped me to understand it.
How do I copy a text file but remove any blank lines held within that text using egrep?
Hi,
i want to search path for file which has a no say ‘7000000000’ in a server , how i can do this ??
please help
I’ve got to list up all files that located in a folder like /usr/local/somefolder
to see every file it uses an absolute path for a command like
…
require once /some path/some file
…
for example
so I need a wildcard showing all files that uses all commands dealing with
absolute paths
for managing a migration to another platform…
i need to get the last line from a match with grep although there are multiple matches
Thanks for the tutorial, i learnt a lot
Great post. Very Helpful.
Wow. This is exactly what I was waiting for.
I have files as below:
contents in ‘tempFile’ file
===================
file1.bak.p
file1.p
abcd.h
abcd.bak.h
how do I search only for the non “.bak: file?
I tried as below but not working
grep -v ‘.*\..*\.[a-z]*’ tempFile > tempFile2
grep -v “.bak” tempFile
actually I need to seach for words that only has one occurance of “.”
as such, ‘abcd.bak.h’ has two “.”
how can i grep logs using today’s date or say last 24 hours.
for ex: grep “logs” messages | grep “Jan 5” — i can find logs for Jan 5 using this syntax but I want to use this in a script where I don’t have to use the date every time instead use something like 24 hours
I know that it should work like this….
grep error /home/armand/Documents/errors.txt
but how do i ignore the ‘shutdown_error’ grep?
Plz tell about:-
$ grep -l”`echo ‘\t’`” foo
here foo is a file name….
now i can reduce my time in study,by using this website….
thanks for that…
Hey that colour thing is not working on my machine….?
How can we grep for patterns in an Arabic file? When I type the pattern to look for, it shows nothing. The file is in Arabic script, but the search on command line does not show that search string?
Can we read the binary file and search for a particular pattern there? Is there any website/ tutorial on using grep with Arabic script?
Thanks
Dear all,
i have a folder consisting of some hundred txt files.Each file has a description about 10 lines ,then followed by six columns and more than 500 rows.My job( for each txt file) is among the six columns i have to search the string(contains numbers) in the second column ,if there is any matches in any row ,then in the output file i want the few specified lines in the description followed by the row which matches the string.so atlast i want single file which contains the desription of the file as well as the rows that matched the string.Thanks in advance..
How to search any string or filname in all the sub-directory starting with same word. Example :
i need to search the word = ‘dataload’ in all the sub-directory which starts with ‘data2011’ in dir: DATA.
Where DATA directory has following sub-directory = data2010Jan, data2010mar, data2010july, data2011jan, data2011aug, data2009dec
grep -r dataload /?folders/DATA/data2011*
Hope that helps 🙂
if you want the results to go into a text file
use
grep -r dataload /?folders/DATA/data2011* > results.txt
then you can nano results.txt or vi results.txt or what ever program you want to use…
I need to know how can i used the line that contain word “accused” without regarding for upper or lower case.using “greb command.
example: greb “accused” file
grep -i “accused” file
How do i search a string in two files.
If some can tell about how to search a particular srting in directory and its sub Directories, It would be of great help.
HI, I wish to ask on how to use grep to produce the output result as below. Thank you very much
Input
FEATURES Location/Qualifiers
source 1..94601
gene 1..2685
Output
FEATURES Location/Qualifiers
source 1..94601
it is very hard to understand the grep command
please easy explanation about grep command
@murugesh March 13, 2011
How do i search a string in two files?
cat file1 file2 | grep string
@N.Srinivasan March 13, 2011
If some can tell about how to search a particular srting in directory and its sub Directories, It would be of great help.
grep -r string /dir/
Hi,
I use a grep command to search a file.
That ouput is sent to a folder.
Since there are no space in the server, its showing an error like no space in desk
Any possibility of zipping the output of Grep command before writing to disk?
Pretty good description thank you
How do i grep for lines containing a specific string, say “forrest”, while not containing another string “gump”?
There is a variant of grep known as gzgrep to search for a term in the argz archives.
Consider the file data.txt which contains the following data (MSISDN, credit, status, error_code, location_id) in the below format
MSISDN,Credit,Status,location_id,Error_code
0123318739,13213,A,300,abcde
0120123456,3423,C,200,xcvfe
0120453576,5563,A,201,fgsa
0110445654,3000,A,400,gcaz
0120432343,3000,A,402,dewa
0129423324,3000,A,206,dea
0104323433,3000,A,303,a
01232132134,3000,A,200,a
0122344242,4233,N,204,ghfsa
————————————————–
my question is how can i perform the follwing query
Try to have a command that can match all the below criteria
• MSISDNs range between 01201xxxxx to 0122xxxxxx
• And have credit over 3000
• Status either A or N
• location_id contains letter ‘a’
• Error_code starting with 2
The output of the command you will use when applied on the above file should be
please i need your reply urgently
ahanks in advance
=================
Consider the file data.txt which contains the following data (MSISDN, credit, status, error_code, location_id) in the below format
MSISDN,Credit,Status,location_id,Error_code
0123318739,13213,A,300,abcde
0120123456,3423,C,200,xcvfe
0120453576,5563,A,201,fgsa
0110445654,3000,A,400,gcaz
0120432343,3000,A,402,dewa
0129423324,3000,A,206,dea
0104323433,3000,A,303,a
01232132134,3000,A,200,a
0122344242,4233,N,204,ghfsa
————————————————–
my question is how can i perform the follwing query
Try to have a command that can match all the below criteria
• MSISDNs range between 01201xxxxx to 0122xxxxxx
• And have credit over 3000
• Status either A or N
• location_id contains letter ‘a’
• Error_code starting with 2
The output of the command you will use when applied on the above file should be
Try this i got correct output.
$grep -w ‘0122476499’ filename |
grep -w ‘45559’ |
grep -v -w ‘3000’ |
egrep -w ‘A|N’ |
grep -w ‘266’ |
grep ‘a’
important change : change the first line into following two lines :
$grep -w ‘0122397399‘ filename |
grep -v -w ‘012005727 |
Thanks alot you are genuios
some of the lines worked normally but when I tried to combine them it gives me error so all iam asking is to give me the whole bulk of code to run it in one sentence. Thanks again man you are really a life saver
BR,
Besso
hi. i m not getting getting exactly what u r asking . they are all piped ones../
u write all these in .sh file then run…also u want to use these code for single files or multiple files.
question : i want to find only the directory in a particular directory.so what is the command in linux to do so.pls help
@swapnil:
find -type d
i want to move few file from one location to another. there is no pattern except for one -> “05_ _2011”. these two underscores can be any number. i am not able to move or do a grepfor this pattern.
let /home/user/folder be the direcrory contains .txt(or any other extensions) files.Some of these files contains the string ’05_ _2011′.We find those files which contains the string ,and copy files to a new location.
Save the follwing code as program.sh file
———————————————-
#! /bin/bash
grep -l ’05842011′ *.txt |
while read line
do
cp /home/user/folder/$line /new/path
done
—————————————-
the files will be copied to a new path with a same file name.
hope it helps.
its a very helpful for me, thank u
Regards,
Faizan Khan
Pakistan Karachi
How to grep a log file
from 07-JUN-2011 01:13:00 to 09-JUN-2011 15:03:04
my date format is 07-JUN-2011 01:13:00
$grep ‘08\-JUN\-2011’ logfile
if we specify time, we need to filter more with grep,that makes code difficult and writing lots of lines.Instead get the list for three days, delete the contents before 07-JUN-2011 01:13:00 and after 09-JUN-2011 15:03:04 in a notepad.
Hope it helps
its a very helpful for me, thank u
Regards,
Gobind
why are all tutorials incomplete?
What are you talking about?
This helps a lot, Could you please explain grep command.
” ls -l | grep -a “^d” | tee dir.lst | wc -l “
The grep will get only name of directories from the ls -l output.
How can I grep for 2 strings (string1 and string 2) in 2 log files: log1 and log2 in one command? I also need to show 3 lines before and 3 lines after each string.
Thanks in advance.
for the first step you use the following command
$ cat log1 log2 | grep ‘string1.*string2′
I didn’t get the appropriate meaning for ’3 lines before and 3 lines after each string’
hope it helps
@lhab
Can you try this and let me know if it suits your requirement:
$ cat log1 log2 | egrep ‘string1|string2′| egrep -A3 -B3 ‘string1|string2’
This is what the bash zealots refer to as unnecessary use of cat.
either
grep -e ‘string1’ -e ‘string2’ log1 log2
or
grep ‘string[12]’ log1 log2
or
egrep ‘string(1|2)’ log1 log2
though… assuming string1 and string2 are completely different / not entirely the same except for the last two into digits then we could use either
egrep ‘(string1|string2)’ log1 log2
or
grep -E ‘(string1|string2)’ log1 log2
or
grep -e ‘string1’ -e ‘string2’ log1 log2 (which I already mentioned)
I meant to say “int digits” referring to integers and not “into digits”.
for the first step you use the following command
$ cat log1 log2 | grep ‘string1.*string2’
I didn’t get the appropriate meaning for ‘3 lines before and 3 lines after each string’
hope it helps
Dinesh,
Thanks for your reply. What I am trying to search for is a log with multiple daily entries. One log may contain many days worth of entries. One day of log entry can be located in 2 different logs (log1 and log2). For example:
1) Let’s say that I want to search all the log entries of July 1, 2011 that are located in log1 and log2.
The first string in the log entry is the date which has the following format: 2011-07-01 and the second string which can be anywhere in the same log entry: ‘transaction failed’ or ‘error’ or ‘unsuccessful’.
So string1 = 2011-07-01 and string2 = ‘transaction failed’ or ‘error’ or ‘unsuccessful’.
2) Each log entry can be up to 6 lines long. Log entries are seperated by 1 blank line and another line says: END OF ENTRY. I believe grep command would only display the line that contains both strings (string1 and string2) but I would like also to display the whole log entry that contains both string1 and string2 if possible.
I have to search for two words..for ex animal …after it is present i need to search for dog …Basically i have to AND both the terms…suggest me the command?
hi rohit
u can use pipelining command
for example
suppose ur file name is animal_list
then u give a command like this
cat animal_list | egrep -i ‘ex | animal’ | grep -i ‘dog’
In RHEL 4 update 8 RAM is 16GB what will be the suggested SWAP and kernel parameters for running oracle 10.2.0.3
very intresting and good way.. thanks
this is useful everyone
this site is very hopeful to me !
thanks to this website , i can lean the grep command esilry
bye. i will expect more precious info .
how to find a string in a file..that string is middle of the file
grep ‘^string’ file name..starting of the line
grep ‘string$’ filename ending of the line
then how to fine that string middle of the line by using grep
can somebody give me examples of
grep –color=auto foo myfile
$ grep –color vivek /etc/passwd
I need to find a string using grep then i want to see the searched text in a specified color where it’s present.
Nice tuts. Thanks!
Hi…. I have a xml file named ” Customer_REPEAT_159.xml”, this file has an element named
940547722
My requirement is to use a shell script to extract the value of the ARC_ACCT_NUM; i.e. 940547722, and rename this file, to (ARC_ACCT_NUM)_CurrentTimestamp, i.e. 940547722_20110825114523.
Can someone help me out in this?
Please let me know, if any further information is required on this…. 🙂
it was realllyyyyyyyy awsoome! really useful! thank you very much!
This tutorial s realy gud..simple and lso 2 point..
I have a line in a file i.e.
How do I use grep and awk to print
a b ?
Wonderful,simple ,nice and clean Thankyou
1) Use grep (or awk) to output all lines in a given file which contain employee ID numbers. Assume that each employee ID number consists of 1-4 digits followed by two letters: the first is either a W or a S and the second is either a C or a T. ID numbers never start with 0s. Further assume that an employee ID is always proceeded by some type of white space – tab, blank, new line etc. However, there might be characters after it, for example punctuation.
What to turn in: Turn in three things:
a. A file with the regular expression which can directly be used by grep (or awk)
b. A text file which you used to test your regular expression. Make sure that you include valid and ‘invalid’ employee IDs, have them at the beginning and the end of lines, sentences, etc.
c. A second document which re-writes the regular expression in a more human-readable form and explains the purpose of the different components of the regular expression. Also include a short explanation of your test cases.
2) Use grep (or awk) to output all the lines in a given file which contain a decimal number (e.g. a number which includes a decimal point). Decimal numbers do not have leading zeros but they might have trailing zeros. Assume the number is always surrounded by white space.
What to turn in: The same three things as above (except, of course, for this problem).
3) Write a regular expression for the valid identifiers in Java. You are allowed to use ‘shortcuts’, but need to make sure that you specify exactly what they are (e.g. if you use digit specify that that means 0, 1, 2, 3, ….9.)
Q1)by using grep command how do display all those lines in a file that has only uppercase characters?
Q2)by using grep select all those lines which has a ?(mark) at the end of line?
Q3) by using grep command how select all those lines which has any of the following patterns ab,aab,aaab or like others?
How can I use grep with wc and uniq commands? I know I have to use piping, but I can’t seem to get the order right. Can someone help?
how to do grep -v ‘pattern1|pattern2|pattern3’ with invert search?
Can anybody give me an idea what these grep commands are doing? I know they are specific to the business process where I am, but any insight would be helpful.
$tzfile is a timezone file
$alist is a file with three lines each with a numeric value
grep NEWPOS $tzfile |cut -c1-4 >$alist
grep FUTQP $tzfile |cut -c1-4 >>$alist
grep CLB $tzfile |cut -c1-4 >>$alist
how do i do this- grep -w “…” filename
with the comand “sed”?
I’m new to linux , I would like to know how to identify the blank files in linux for example
[root@xxxxxx]# cat dfpAL52sS5028817
[root@xxxxxx]#
[root@xxxxxx]#
[root@xxxxxx]#
I would like to identify the files that shows blank as above , can any one help me this.
advance thanks,
Siva.
while some of this may work, it’s a rather inefficient way to do it. You can read the man page for both ps and grep by running the commands “man ps” and “man grep” (without the quotes) to get a good idea of what all the options are. In doing so you can see that you can specify the command you are looking for in ps using the -C option, you can format the output to look how you want with the -o option and you can remove the headers which usually become negligible when using the -o option by adding the –no-headers option. Additionally with grep their is a -q option which causes grep to be quiet so there would be no need to redirect output to /dev/null and another useful option would be -w which matches word only. Additionally, if you run the command “help if” (without the quotes) or “man bash” and skip to the if section, you will see that the if clause evaluates the return of a command. “[” in a if clause is a command (either a shell built-in usually or can be an external command. You likely have both but the shell built-in takes precedence. Because of this, you can use grep as the command if looks at instead of the [ command/clause and narrow down your code a lot more to look something like this:
I’m using $
Again, the $<> isn’t portable and may not work outside of bash but, on the other hand, bash has been around longer then Linux (bash since 89, Linux since 91) and is the default shell on most Linux distros so it’s there to use and really worth it.
Another plus about using bash, again, this isn’t portable and may not work outside of bash but you can use if [[ my_test ]] instead of if [ my_test]. [[ should only be a shell built in. What I mean by this is that [ can either be a shell built in function (and most commonly it’s the shell built in you use or [ can also be a command. [[ is almost never the name of a command and hence why it’s not portable but if you are using bash and you probably should be unless you know why you want to use another shell more but if you are using bash then [[ and ]] is less error prone then [ and ] and allows you to perform multiple checks within the same test clause, for example if you wanted to test to make sure one check is correct or another check is correct using [ and ], the safest way to do so would be to have to separate if statements outside of each other both performing the same action i.e.
In theory you can use:
However chaining or statements like that in multiple commands to the if statement to see if either one is true is frowned upon and is said that it may cause unexpected results. The proper way to do this from bash would be:
If you try to use:
then it will fail because it will treat the || inside the [ and ] as a bash || statement between two command thinking “2 == 2 ]” is a second command and will complain that you are missing the closing ] on the first command. Using [[ and ]] you can also use an AND clause to all tests are true instead of if any one test is true, for example
For more details on all the operators you can use within [ ] and [[ ]], run the commands “help test”, “help [” or “man bash” (without the quotes) and if you look at the man page for bash, jump down to the section “CONDITIONAL EXPRESSIONS” (again, without the quotes).
Another handy test method to use inside bash is (( and )) for number only comparison. You can use [[ and ]] to test if a file exists or if a string is the string you want etc but (( and )) are only for numbers (more specifically integers but I’ll dive into that in a moment). which can help make sure you are not accidentally testing something you shouldn’t be. Also you can use “declare -i” (sans the quotes) to define a variable that can only hold an integer and if anything is assigned to it that is not an integer then it will default to 0.
You can store decimal numbers in regular variables though there is no special var designed only for decimals. There are a lot of different ways to test decimal numbers but the best, IMHO, is using the command bc command. You can use this inside a (( )) test by calling the bc command using command substitution with $(command). People often use back ticks, ” `command` ” (sans the double quotes), for command substitution which, again, back ticks are portable and $( ) doesn’t work in all shells however, if you are using bash and you probably should be using bash then $(command) is more more powerful and back ticks are much more prone to error. When using bc to perform a comparison, for example, if x jetole Dec 2, 2011 @ 13:53
I don’t know what the name of the oracle server is. In my first example I used:
This was assuming the name of the command running is oracle however if you know part of the command name then you can find the exact command name by running:
The output ucmd shows only the command running without any arguments unlike “-o cmd” which shows the command and all arguments so when you use “-o ucmd” and do a case insensitive search for oracle, it will return any commands that are either named oracle or have oracle as part of their name but it will not return the grep command because ucmd isn’t showing arguments so the ps listing, for the line which matches grep will just show “grep” and not “grep -i oracle”. When you run the above command to find your commands name, you can replace oracle with all or part of the command you are looking for and it will return any patches, case insensitive (-i option for case insensitive).
so much helpful nd clear document………………………………………
Источник