Photo courtesy of Alexôme’s
You should get a grip on the Linux grep command.
This is part of the on-going 15 Examples series, where 15 detailed examples will be provided for a specific command or functionality. Earlier we discussed 15 practical examples for Linux find command, Linux command line history and mysqladmin command.
In this article let us review 15 practical examples of Linux grep command that will be very useful to both newbies and experts.
First create the following demo_file that will be used in the examples below to demonstrate grep command.
$ cat demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. Two lines above this line is empty. And this is the last line.
1. Search for the given string in a single file
The basic usage of grep command is to search for a specific string in the specified file as shown below.
Syntax: grep "literal_string" filename
$ grep "this" demo_file this line is the 1st lower case line in this file. Two lines above this line is empty. And this is the last line.
2. Checking for the given string in multiple files.
Syntax: grep "string" FILE_PATTERN
This is also a basic usage of grep command. For this example, let us copy the demo_file to demo_file1. The grep output will also include the file name in front of the line that matched the specific pattern as shown below. When the Linux shell sees the meta character, it does the expansion and gives all the files as input to grep.
$ cp demo_file demo_file1 $ grep "this" demo_* demo_file:this line is the 1st lower case line in this file. demo_file:Two lines above this line is empty. demo_file:And this is the last line. demo_file1:this line is the 1st lower case line in this file. demo_file1:Two lines above this line is empty. demo_file1:And this is the last line.
3. Case insensitive search using grep -i
Syntax: grep -i "string" FILE
This is also a basic usage of the grep. This searches for the given string/pattern case insensitively. So it matches all the words such as “the”, “THE” and “The” case insensitively as shown below.
$ grep -i "the" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. And this is the last line.
4. Match regular expression in files
Syntax: grep "REGEX" filename
This is a very powerful feature, if you can use use regular expression effectively. In the following example, it searches for all the pattern that starts with “lines” and ends with “empty” with anything in-between. i.e To search “lines[anything in-between]empty” in the demo_file.
$ grep "lines.*empty" demo_file Two lines above this line is empty.
From documentation of grep: A regular expression may be followed by one of several repetition operators:
- ? The preceding item is optional and matched at most once.
- * The preceding item will be matched zero or more times.
- + The preceding item will be matched one or more times.
- {n} The preceding item is matched exactly n times.
- {n,} The preceding item is matched n or more times.
- {,m} The preceding item is matched at most m times.
- {n,m} The preceding item is matched at least n times, but not more than m times.
5. Checking for full words, not for sub-strings using grep -w
If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines.
The following example is the regular grep where it is searching for “is”. When you search for “is”, without any option it will show out “is”, “his”, “this” and everything which has the substring “is”.
$ grep -i "is" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. Two lines above this line is empty. And this is the last line.
The following example is the WORD grep where it is searching only for the word “is”. Please note that this output does not contain the line “This Line Has All Its First Character Of The Word With Upper Case”, even though “is” is there in the “This”, as the following is looking only for the word “is” and not for “this”.
$ grep -iw "is" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. Two lines above this line is empty. And this is the last line.
6. Displaying lines before/after/around the match using grep -A, -B and -C
When doing a grep on a huge file, it may be useful to see some lines after the match. You might feel handy if grep can show you not only the matching lines but also the lines after/before/around the match.
Please create the following demo_text file for this example.
$ cat demo_text 4. Vim Word Navigation You may want to do several navigation in relation to the words, such as: * e - go to the end of the current word. * E - go to the end of the current WORD. * b - go to the previous (before) word. * B - go to the previous (before) WORD. * w - go to the next word. * W - go to the next WORD. WORD - WORD consists of a sequence of non-blank characters, separated with white space. word - word consists of a sequence of letters, digits and underscores. Example to show the difference between WORD and word * 192.168.1.1 - single WORD * 192.168.1.1 - seven words.
6.1 Display N lines after match
-A is the option which prints the specified N lines after the match as shown below.
Syntax: grep -A <N> "string" FILENAME
The following example prints the matched line, along with the 3 lines after it.
$ grep -A 3 -i "example" demo_text Example to show the difference between WORD and word * 192.168.1.1 - single WORD * 192.168.1.1 - seven words.
6.2 Display N lines before match
-B is the option which prints the specified N lines before the match.
Syntax: grep -B <N> "string" FILENAME
When you had option to show the N lines after match, you have the -B option for the opposite.
$ grep -B 2 "single WORD" demo_text Example to show the difference between WORD and word * 192.168.1.1 - single WORD
6.3 Display N lines around match
-C is the option which prints the specified N lines before the match. In some occasion you might want the match to be appeared with the lines from both the side. This options shows N lines in both the side(before & after) of match.
$ grep -C 2 "Example" demo_text word - word consists of a sequence of letters, digits and underscores. Example to show the difference between WORD and word * 192.168.1.1 - single WORD
7. Highlighting the search using GREP_OPTIONS
As grep prints out lines from the file by the pattern / string you had given, if you wanted it to highlight which part matches the line, then you need to follow the following way.
When you do the following export you will get the highlighting of the matched searches. In the following example, it will highlight all the this when you set the GREP_OPTIONS environment variable as shown below.
$ export GREP_OPTIONS='--color=auto' GREP_COLOR='100;8' $ grep this demo_file this line is the 1st lower case line in this file. Two lines above this line is empty. And this is the last line.
8. Searching in all files recursively using grep -r
When you want to search in all the files under the current directory and its sub directory. -r option is the one which you need to use. The following example will look for the string “ramesh” in all the files in the current directory and all it’s subdirectory.
$ grep -r "ramesh" *
9. Invert match using grep -v
You had different options to show the lines matched, to show the lines before match, and to show the lines after match, and to highlight match. So definitely You’d also want the option -v to do invert match.
When you want to display the lines which does not matches the given string/pattern, use the option -v as shown below. This example will display all the lines that did not match the word “go”.
$ grep -v "go" demo_text 4. Vim Word Navigation You may want to do several navigation in relation to the words, such as: WORD - WORD consists of a sequence of non-blank characters, separated with white space. word - word consists of a sequence of letters, digits and underscores. Example to show the difference between WORD and word * 192.168.1.1 - single WORD * 192.168.1.1 - seven words.
10. display the lines which does not matches all the given pattern.
Syntax: grep -v -e "pattern" -e "pattern"
$ cat test-file.txt a b c d $ grep -v -e "a" -e "b" -e "c" test-file.txt d
11. Counting the number of matches using grep -c
When you want to count that how many lines matches the given pattern/string, then use the option -c.
Syntax: grep -c "pattern" filename
$ grep -c "go" demo_text 6
When you want do find out how many lines matches the pattern
$ grep -c this demo_file 3
When you want do find out how many lines that does not match the pattern
$ grep -v -c this demo_file 4
12. Display only the file names which matches the given pattern using grep -l
If you want the grep to show out only the file names which matched the given pattern, use the -l (lower-case L) option.
When you give multiple files to the grep as input, it displays the names of file which contains the text that matches the pattern, will be very handy when you try to find some notes in your whole directory structure.
$ grep -l this demo_* demo_file demo_file1
13. Show only the matched string
By default grep will show the line which matches the given pattern/string, but if you want the grep to show out only the matched string of the pattern then use the -o option.
It might not be that much useful when you give the string straight forward. But it becomes very useful when you give a regex pattern and trying to see what it matches as
$ grep -o "is.*line" demo_file is line is the 1st lower case line is line is is the last line
14. Show the position of match in the line
When you want grep to show the position where it matches the pattern in the file, use the following options as
Syntax: grep -o -b "pattern" file
$ cat temp-file.txt 12345 12345 $ grep -o -b "3" temp-file.txt 2:3 8:3
Note: The output of the grep command above is not the position in the line, it is byte offset of the whole file.
15. Show line number while displaying the output using grep -n
To show the line number of file with the line matched. It does 1-based line numbering for each file. Use -n option to utilize this feature.
$ grep -n "go" demo_text 5: * e - go to the end of the current word. 6: * E - go to the end of the current WORD. 7: * b - go to the previous (before) word. 8: * B - go to the previous (before) WORD. 9: * w - go to the next word. 10: * W - go to the next WORD.
Additional Grep Tutorials
- 7 Linux Grep OR, Grep AND, Grep NOT Operator Examples
- Regular Expressions in Grep Command with 10 Examples – Part I
- Advanced Regular Expressions in Grep Command with 10 Examples – Part II
- Search in a *.bz2 file using bzgrep, and *.gz file using zgrep
Awesome Linux Articles
Following are few awesome 15 examples articles that you might find helpful.
Comments on this entry are closed.
You have a small glitch:
>> 4. Match regular expression in files using grep -i
Don’t you mean:
4. Match regular expression in files using grep -e
The rest of the post is great.
Joao,
Thanks for pointing it out. I have corrected it. Also, we can do REGEX without the option -e as shown in the example #4.
From Man Pages:
Hi:
FYI, tip 14 will be
2:3
8:3
on Ubuntu system. (including the \n character I guess
Dragon,
Thanks for pointing it out. I’ve corrected it.
I find very useful the following command, when you have to deal with a very lengthy configuration file full of comments:
grep -v -E ‘^\#|^$’ /etc/squid/squid.conf
It skips every line beginning with an hash (#) or empty, so you can see at a glance the 15 lines edited out of a +4400 lines text file.
BTW interesting topics, great posts…
help me
how to bzgrep : ^C02
but ^C is count as one special character,
in this word:
data1^C02data2
thank’s
@Francesco Talamona,
Thanks a lot for sharing your grep command example. Yes. all those empty lines and comment lines can get very annoying when you do grep. So, it is an excellent idea to hide them in the grep output with your examples.
@albar,
try like this
grep ‘\^C02’
@sasikala ,
i do have try that too, but still got nothing,
but it works when ^ and C count as two character
thank’s
@albar
You should type ^C as ctrl-v + ctrl-c in grep as single character as
$ grep ^C02 file
Dont escape, dont type it as ^ C as two characters. Hope this helps.
@sathiya,
god bless u all
it work’s thanks
Hi
I am trying to exclude the last word of all the line like sync.php, uploads.php, backup.php
File text include as below
/usr/home/htdocs/drag-and-drop/htdocs.php
/usr/home//htdocs/sms/publish/pages/sync.php
/usr/home/htdocs/track/backup.php
/usr/home/htdocs/smstest/smstest.php
/usr/home/htdocs/uploads.php
/usr/home/htdocs/017/backup.php
How can I achieve that using grep or sed or awk
Also how I can use “*” wildcard in sed command like to replace *.php to *.txt or any other extension.
Thank you in advance.
Manish
Are you restricted to sed or awk?
1)
dirname ‘/usr/home/htdocs/drag-and-drop/htdocs.php’
/usr/home/htdocs/drag-and-drop
2)
rename does what you want
Hi,
Those lines are the contents of the text file and I don’t want to change the actual directory or the file on server. I want to change the contents of the file where all file file names ending at the line should be removed. So the final file contents should look like this
cat filecontenet.txt
/usr/home/htdocs/drag-and-drop/
/usr/home//htdocs/sms/publish/pages/
/usr/home/htdocs/track/
/usr/home/htdocs/smstest/
/usr/home/htdocs/
/usr/home/htdocs/
I think rename would not help here in editing file contents.
Thank you
Manish
rev filecontenet.txt | cut -d’/’ -f2- | rev
rev filecontenet.txt –> reverses the file and pipes to cut command.
cut -d’/’ -f2- –> cuts off the first field ( cuts off last field, as it is reversed ).
rev –> prints the output given order.
Manish,
I believe you’re looking for the following
sed -e ‘s/.php$//’ filecontenet.txt
Sorry, didn’t read your requirement carefully.
Try this:
sed -e ‘s/\/[^/]*.php$/\//’ filecontenet.txt
Hi
Thank you to Sathiya Moorthy and P0B0T.
Both solution worked very nicely for me.
P0B0T can you explain how your command works for each defined option ’s/\/[^/]*.php$/\//’
Thank you
Manish
The above info on grep is really great. I want to search for a string in all the files in the directory and add a $ symbol at the start of the searched line and save in the same file.
@mano
More than using grep for this requirement, you can use sed which is:
sed -i ‘s/.*abc.*/$&/’ *
-i : edit the input file.
s/// : substitute the matched pattern with the replacement string.
/.*abc.*/ : match the string abc
/$&/ : Replace with $ followed by matched string.
* : all the files in the current directory.
This is one way of satisfying your requirement, there may be other efficient ways.
Hope this helps.
Hi SathiaMoorthy, Thank u so much. it works fine. If I need to search for files in all subdirectories, how should this “sed” command modified?
Thanks in advance.
mano
@mano
Modification in sed command is not needed.
To search for all files in the subdirectory.
find . -type f
Execute the command on all those files with -exec.
find . -type f -exec sed -i ‘s/.*abc.*/#&/’ {} \;
But think twice before executing this command, because it will recursively edit all the files. Taking backup before executing this command is wise.
Refer the earlier article linux find command examples.
Hi,
I want to grep next 3 words in a line from the matching criteria word..
like if the line is
This is -g gateway -e enterprise -s server
Then I want to grep “-g gateway -e enterprise” from the line
Can you please help me in this case.
Here gateway and enterprise value can be anything so need to grep next 3 words starting form “-g”
@Vidhya
$ grep -o -E — “-g \w+ -e \w+” FILENAME
-g gateway -e enterprise
Explanation of the above command.,
-o : only matching ( point 13. )
-E : extended regexp
— : indicate end of options
\w+ : word
Hi Sathiya,
Its not working.
It says
grep: illegal option — o
grep: illegal option — E
Usage: grep -hblcnsviw pattern file . . .
I am working on Solaris and setting shell as bash.
grep version on solaris is little older and as man would show you all these options are not available, so you can try ack (standalone) version which is very powerful and requires only perl to be installed.
Hi,
How to use grep to find lines containing multiple strings
ex: line1:Today is oct 7, wednesday. not 8th
line2: This is not summer.
line3: when is summer?
I want to return line2 containing strings “not” and “summer” both.
Thank You.
@learner
There are several ways possible, use the one which you find as appropriate.
@SathiyaMoorthy
Thank You for your very quick reply.
My question was not piping and hard coding every string , as i mentioned multiple strings, i was looking for something in likes of
grep -F ‘string1
string2
string3
string4
…..
stringn’ filename
which returns single occurrence of something like either string1 ,string2,.. stringn or all .., what i wanted was only string1 and string2 and ……. stringn begin returned.
[please note that i will be provided with strings as newline separated strings ,which i don’t want to parse again and i have constraint of using grep only]
Thank You.
Hi,
I need to sthing like this
I have a file containing 400 domainId values seprated by new line
ex. domain.txt
domain1
domain2
domain3…
I have a script that takes each domain and calls an api that returns me an xml.
like this for each domain
val1
domain1
val2
val3
val4
XXX
val1
now i want to spit out the domain name in a file that does not matches domainid value XXX.
how can i do it using grep
TIA
Hi,
I need to sthing like this
I have a file containing 400 domainId values seprated by new line
ex. domain.txt
domain1
domain2
domain3…
I have a script that takes each domain and calls an api that returns me an xml.
like this for each domain
<tag1>val1</tag1>
<domain>domain1</domain>
<tag2>val2</tag2>
<tag3>val3</tag3>
<tag4>val4</tag4>
<domainid>XXX</domainid>
<tag5>val1</tag5>
now i want to spit out the domain name in a file that does not matches domainid value XXX.
how can i do it using grep
TIA
Hi,
The options mentioned in point 6 for displaying the context with A, B, & C does not seem to work on Solaris 10 with both grep & egrep
Is there a version of this grep available for Solaris?
Thank you,
Varun.
Does the -b (byte offset) work when greping binary files? I do not get an offset returned when I grep a binary file, but I do when using a text file. I am using grep under Cygwin.
thanks very much for this tutorial. it is very helpful..
Awsome tutorial!
I’m reading all your blog, its amazing!
Hai.. I want to Parse my file .. Word to Excel .. so tell me some grep & cut commands…
Whats the difference between $ grep -c ill memo and $ grep -n ill memo?
hi
i got 1 problem…how can i find a numbers like 99,000,000.95 in my server database using unix command..
tq
content was very useful
Hi,
Those lines are the contents of the text file and I don’t want to change the actual directory or the file on server. I want to change the contents of the file where all file file names ending at the line should be removed. So the final file contents should look like this
cat filecontenet.txt
/usr/home/htdocs/drag-and-drop/
/usr/home//htdocs/sms/publish/pages/
/usr/home/htdocs/track/
/usr/home/htdocs/smstest/
/usr/home/htdocs/
/usr/home/htdocs/
I think rename would not help here in editing file contents.
for this question , awk really helpful with single line command
go to the current directory
ls -l | grep -v ^d | awk ‘{print $9}’ > new.txt
$9 — is the last filed which is filename only when u list with option ls -l ,
new.txt contains only the filenames which you wnated to filter out
nice article
Excellent stuff, just loved grep -A,B,C options
and
grep -o “xxxx.*yyyy” kinda commands.
This will help me a lot, I used awk more in my shell scripts, But I have got a new friend “grep” for some selective printing 🙂
I have just finish reading this wonderful article. Let me answer this:
Whats the difference between $ grep -c ill memo and $ grep -n ill memo?
grep -c return the number lines that matched ill in memo.
grep -n return the matched lines with line-number as prefix.
how to grep a statement contain ‘*’ from a file at the same time to match the first character too.
example the statement in filename profile.txt :-
“Mary stay at uttana*istana with her grandmum”
current grep statement :-
grep “^Mary stay at uttana*istana” profile.txt
result: no row matched the grep statement because of *
How to use grep command for the combine condition of statement with * and match the front word?
In bash script without using perl, how i can grep a number from a file if there exists a number greater than 80 in that file.
grep -c “pattern” filename returns the number of lines that matches the pattern, even if the pattern occurred for more than one time in any line. Is there any option to know how many times the pattern matched in a file?
HI,
I am new to linux…
can you tell me how to exit from grep command….
mistakenly i type grep filename
But it’s nothing shown…. pls looking for quick reply…
@mathan
There is nothing like exiting from grep.
First argument to grep is taken as PATTERN, not as filename. So as far as i understand it is waiting for input to match. So just exit from it using CTRL+D.
Nice article. Thanks.
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
Is there a way to grep for a word on in a file and return that line plus the next?
@ Lou:
cat testfile.txt
first line
matching line
following line
ending line
grep matching -B 1 testfile.txt
first line
matching line
really to nice and too simple to understand,
thats great
thank you
PLEASE HELP ON QUESTION B.
You are searching a file for lines that contain US state abbreviations in parentheses. e.g.: (ma),(NH),(Ky), etc. So you decide to match any line containing ( ) with exactly two characters (not letters) in between.
A) What grep will get this done?
My Answer—> grep ‘([a-zA-Z][A-Za-z])’ file
You now notice that some of the lines that the grep from part A matched contain the the string (expired). You want to eliminate these lines from your output, so you decide to pipe your output to another grep.
B) What will the new command be? (both greps with the pipe)
My Answer —> grep –v grep | grep ‘([a-zA-Z] [A-Za-z])’ ——-> PLEASE HELP!
@Nikita:
One step is enough:
egrep ‘\([a-zA-Z]{2}\)’ file
How to display all lines that have less than 9 character in a file
I’m new to linux; was wondering what does \# after the grep command accomplish, as shown in the example below?
grep \# input*.txt | awk ‘{print $4}’ | sort | uniq > output.txt
thank you
For a given patern like
Fri Nov 26 16:04:52 2010
I want to grep for all the lines in a file having the above format.
But I have all the values except for the time, that is “16:04:52 ” , the data I have is
“Fri Nov 26 2010 ” . The file is having 5 years of date with the timestamp as specified above.
Please let me know How shall I grep the file to get all the lines on the date “Fri Nov 26 2010 ” .
thanks
i have a doubt here i tried to look at output of cmd
grep “[^A-Z]” file.txt
this is showing all characters excluding capital letter
what does this command actually do
HI i have a file with this values
100 first line
101 second line
101
102
102
109
now i need a script that can take two lines and find which is greatest
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.)
Paul
grep \# input*.txt | awk ‘{print $4}’ | sort | uniq > output.txt
Since # is a special character,we are treating # as # by putting backslash infront of that.
Noe Greap searches for pattern # in a list of file starting as input and nding a txt and then awk prints the 4th field and sort is doing sorting the 4th field returns from awk and unis is doing uniq operation.
Shyam
grep “[^A-Z]” file.txt
Grep will print the lines that does not start with CAPTIAL LETTERS.
Using ^ inside the [] will do the work opposite to the pattern what you have been searching for …
Just a minor thing the last result line is removed in the example above, this should be the result:
$ grep “this” greptest.txt
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.
awesome. thanks a lot.
For example my data is (file.ave) :
MRR 120101000000 UTC+07 AVE 60 STF 150 ASL
H 150 300 450 600 750 900
TF 0.0149 0.0515 0.1171
F00 -67.04
F01 -69.27
I use grep as:
grep -r ‘MRR’ *.ave > time_0101.txt. In this case all file goes to time_0101.txt, I have many files and I need each output goes to specific file name. Any idea ? And how to use grep to take F00 and F01 ? If I use grep -r ‘F’ *.ave, the first line will be taken also because of STF, Thanks for help..
Thank you 🙂
here my question is in a directory i have 10 files.some files contains size in kb’s and some files contains size in mb’s…..i want display the files only which file size is more than 1 mb……
could anybudy help to find answer for this question….
Great post! It was very useful! thanks a lot! 😉
To answer Chinna… If you have some files showing M, and some K, then your “ls” command is probably running on a Linux box, and using the “-h” option.
The preferred method would be NOT to use the “-h” option, and let “ls” print file sizes in bytes, which means that your script will be able to get the same units+detail for all file sizes listed.
Then you can use “awk” to filter out files where $5 (5th field) is over 1Meg, like this:
/bin/ls -l | awk ‘$5>=2^20’
If you only want file names, not ‘ls’ style list, then have awk give you that part of output:
/bin/ls -l | awk ‘$5>=2^20{print $NF}’
Note: this does not like file names with spaces…
—-
notes for Other postings on this thread:
To: Francesco Talamona
(who was using “grep” to remove ##_comments from long config files)
grep -v -E ‘^\#|^$’ /etc/squid/squid.conf
You may want to remove comments that do NOT start on the first char of a line,
and ‘sed’ is more useful for that
sed ‘s/#.*$//;/^[ ]*$/d’ /etc/squid/squid.conf
This will remove comments from each line, then discard the line if blank, or only spaces remain.
=========
Also, where the -B and -A options are described for “grep”…
This is for GNU/Linux, and not supported for most Non-Linux boxes.
#–JETS
Hi expert,
i am new to unix env…
try to use certain command to help me generate 1 output file as below:
input file:
A
A/I 0.2 0.3 0.8
B
B/I 0.6 0.8 0.9
C
C 0.8 2.1 6.0
I just want to grep all A B C only, where want to skip the line which have the number together. And my output file pattern is A B C D…etc ( A, B,C all are a word).
mean i want first,second line, and skip 3rd & 4th lines, thanks for help.
How do you find using regular expression, characters beginning with and ending with any characters.
In AXyz122311Xyslasd22344ssaa Aklsssx@sdddf#4=sadsss kaaAASds
How do we get the characters “slas” out that begins with “11Xy” and ends with “d223” in UNIX using regular expression?
echo $MSG | grep -o ‘(?<=11Xy).+(?=d223)'
@krishna,
echo $MSG | grep -o 11Xy.*d223
i need answer for the following question
using grep, determine count of and print the list of words having uppercase letters when the input sentence is given in command line
I know this is a simple grep or grep/sed question:
I have a log file with identified errors.The errors will lines containing the words “Patient ID: 12345678999” (quote marks are mine). i substituted the number 12345678999 for a real number. The real number will be any combination of 11 integers. So I would want to grep for Patient ID: 12345678999 but just end up with the numbers themselves, not the rest of the lines.
Example of result I would like:
12345678999
23678900456
Thanks
Hi,
Is there any way to find strings longer than 50 charachter within files with grep?
Thanks,
It’s really great …….
Helo anyone tell me how find word from directory contains number of files using grep command and any other command
Hey i am trying to just write first simple script. Here what I am trying to do is pass the word which I want to find in array from command line. After that it should print all entires which contain that word. Say I want to find Jacob from command line but its not returning any result.
#! usr/bin/perl
use Fcntl;
print “content-type: text/html \n\n”;
print “Enter word : “;
$word = ;
@myNames = (‘Jacob’, ‘Michael’, ‘Joshua’, ‘Matthew’, ‘Alexander’, ‘Andrew’);
@grepNames = grep(/$word/, @myNames);
foreach $Names(@grepNames)
{
print $Names;
print “\n”;
}
Answer to Palash:
$grep -o pattern file name | wc -w
Answer to SANKET:
if I understand your question correctly:
ls -1 | grep “P.*Entity\.java” –count
will do a listing of your directory, send it to a grep search, and then count the matches, many people would drop the -1 and abbreviate the –count to:
ls | grep “P.*Entity\.java” -c
hi there!
needed help here..
how to display counts of ids in a file next to each other ?
ex:
file name: images01.txt
ids present in the file: 10001,10002,10003,10004
to-display: id followed by counts
10001 = 100
10003 = 50
Helllo ,
i want to run a script on linux terminal when i press the submit button on webpage…
it is possible..?
Mr. Anonymous,
Do you think this is the right forum to ask this question?
By the way, this can be handled through PHP. Google it and find it how. Post in a relevant thread if you face difficulties.
Regards
Vikas
i want only single command,
i.e lines starting with $
#1 – “$ grep “this” demo_file” – returned two lines:
“this line is the 1st lower case line in this file.”
“Two lines above this line is empty.”
Shouldn’t it also also include this line?
“And this is the last line.”
Thanks or the article, I’ve chosen today to get my grep on!
Hi All,
Thank you very much for this website.
I have one query:
How to search directory by name.
Suppose, I want to store all the directories in an array with name “abc” only.
I tried this:
$name=”abc”;
@array_1= grep (/$name/), $curr_dir; #curr_dir is any directory
________________________________________________________________________________
But the problem is, this command also matches directory with name “abcd”, “aabc”, “abc24” etc
Can you please help me?
How can I find any lines in a source file that contain 2 search strings. When I tried using a pipe I got an error. Am running on TNS Guardian (not unix).
Thanks!
# ifconfig
eth0 Link encap:Ethernet HWaddr 54:04:a6:8a:42:58
inet addr:10.2.0.170 Bcast:10.2.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:95309 errors:0 dropped:0 overruns:0 frame:0
TX packets:45 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:8865945 (8.4 MiB) TX bytes:5438 (5.3 KiB)
From the above input i want to grep only IP address and subnetmask, that single grep command should be capable to do grep for any ip and any subnetmask. Here i have 10.2.0.170 as IP and subnetmask as 255.255.255.0, so i want to grep only IP and subnetmask.
If i have 1.1.1.1 as IP and 255.128.0.0 as subnetmask in this case the “same command” should capable to do grep IP and subnetmask
Thanks in advance
$ grep -l this demo_*
demo_file
demo_file1
okay. How do you find all files with a given extension using grep ?
Hi,
I have query below:
Sample data file:
26/Jul/2013:11:57:24 -0400 TAN101 active
26/Jul/2013:11:55:24 -0400 TAN102 active
26/Jul/2013:10:55:24 -0400 TAN101 Idle
26/Jul/2013:10:50:24 -0400 TAN103 idle
26/Jul/2013:10:53:24 -0400 TAN103 active
26/Jul/2013:10:43:24 -0400 TAN103 active
Query is:I want the output as group by count.I mean number of records with TAN101,number of records with TAN102,number of records with TAN103 .
TAN101 2
TAN102 1
TAN103 3
Please help me .
How can I grep this ?
if [ “$EUID” = “0” ]
I want to grep this from /etc/profile and add somelines below it
Hi,
I am beginner in using Linux Grep command and I got search for words with “489” in a file as follows:
LRD489E
LRD489
LR489-SPAD
LR489(W)
U489-AB
I tried using grep command as follows:
egrep -o ‘[A-Z]*489[A-Z]*’ FLG.id
the results I get
LRD489E
LRD489
how to get
LR489-SPAD
LR489(W)
Any help appreciated.
Remove tons of abc files
ll | grep abc | awk ‘{print “rm “$8” “}’ | csh
Note:
“$8” — column 8 of ll comand
Hi,
could you please tell me what does “grep -i xyz | grep -v grep” means????
grep -A or -B or -C does not work usually. is there any sed, awk or any other function that can perform an equivalent operation? what grep utility will I need to run these parameters?
Nice Tutorial …
HI Sandeep ,
store input in file named “GroupFile”
grep -o “\(TAN[[:digit:]]\+\)” GroupFile | sort | uniq -c
Dear Sir:
I have a file… in which I intend to extract the pattern (a few lines) starting
with “set_multicycle_path” then some string (*) then “-from” then some string (*)
then “-through ” then some string (*) then “-end ” then some string (*), where
these strings have variable lines, and then the end of these strings afterwards were ]
How to use grep (but not a perl) to extract these lines?
Thanks
Nice posts……
cat myfile.txt |grep *.al > output.txt
I want to grep a file that contains repetition of words (in this case “.al”) using the command above. But I want only one occurrence of each word to be written to another text file called “output.txt”. How can I use the grep command to accomplish this?
To be a bit clearer on my request above…..
In myfile.txt, there could be two or more lines with “46.al” for example but I want only one line of “46.al” to be written to output.txt.
Say for example myfile.txt contains the following lines:
46.al
477.al
446.al
46.al
xyz.al
46.al
46.al
I want “output.txt” to contain the following: 46.al, 477.al, 446.al, xyz.al
Hi,
Is there any grep for the below mentioned scenario.
In file.txt file,
line1
line2
line3
Function(“line1”,
“line2”);
line2
line3
.
.
Now i want to grep only the word ‘line 2’ from the function
How its possible any idea
TIA
I want to use grep twice for 2 conditions in a single search….let’s say i want to search all fies modified on 10-Dec-13. So in my current directory i m typing…below commad for result.
ls -lt | grep -c “^-” | grep “10 Dec”
but the above command is not working
@SP
Use below command
ls -lt | grep -i “Dec 10”
how can I grep a file web.log which contains \\ with mostly no data, however, I would like to find only those values of swingSACovering that HAVE data. In other words, there may be 4000 or so xml elements which do not contain any values. But 2 or 3 will contain data with 6 digits, such as 148231
\148231\ I only want to find the data elements with data.
if we want to find a particular word from a text file what command should i use can anyone help me with shell script..
example
i have more than 16000 lines in which i have to find the occurence particular word
hi
i am using the grep command to search for exceptions.
grep -w exception server.log
This is giving me the output as,
2014-05-19 09:48:17,523 346652103 INFO (Thread-4038 (HornetQ-client-global-threads-573435074):) END – processException:: exception logged into database
which is just the first line of the exception
how to capture the whole exception !
Can someone help?
How do I bzgrep : ^C02 when ^C is count as one special character, such as in this word:
data1^C02data2 ?
How to search for lines that have only single dot in it .
#grep “^ *\.” abc ….. to search lines that have only dots it in .i.e no matter how many dots , but only dots in line .
But to search for lines that have only single dot in it ?????
I’m not very good with linux/unix, and you kept the language simple, along with the examples, so I could follow it without difficulty.
Now I’m a whole lot more confident on how to use grep.
Thank you very much, this is a great article.
How to fiilter the Attributes in a file..
Ex:- If a file has 10 fields——->How can we filter 1,3,5,7,9 fields
Hi Sandeep,
awk would be easiest for your requirement. Try this
cat /your/file | awk ‘{ print $1 “\t” $3 “\t” $5 “\t” $7 }’
Regards,
Vikas
thanks, very usefull command.
how to linux shell pipeline do?
grep nd xyz | wc-i
My Goal is to be able to grep a large directory with Log Files, for any and all items contained in a list and output to a separate file all information that matches.
for example the list will contain multiple IP’s and I want to grep many logs files for any of the matching IP’s
o be a bit clearer on my request above…..
In myfile.txt, there could be two or more lines with “46.al” for example but I want only one line of “46.al” to be written to output.txt.
Say for example myfile.txt contains the following lines:
46.al
477.al
446.al
46.al
xyz.al
46.al
46.al
I want “output.txt” to contain the following: 46.al, 477.al, 446.al, xyz.al
my file has
123
124
125
135
134
136 and i want to display thoz with 4 and 6
pliz help me nw now
Superb…Explained very well…..
Hello All,
New to Unix.
I am not sure whether to use grep or awk for my below requirement.
1) Read a file and move it line by line to a different file
2) If a part of the line has a particular string, then instead of writing the string, we have to pull instead data from a different file.
Let me know if you have any further questions.
Regards,
Vasanth
Great post, thank you!!!!
Just one question how do you revert the following:
$ export GREP_OPTIONS=’–color=auto’ GREP_COLOR=’100;8′ ?
Hi,
I am very new to scripting and just trying something, I have written simple script and doing grep to the process and checking the count. but when I debug this script, I am getting something else. Please see the below script and debug output :-
SCript :-
monname=$1
NUM_PROC=$(ps -ef | grep wd.sap* | grep -v grep | wc -l)
if [[ $NUM_PROC -gt “0” ]]; then
/usr/lpp/OV/bin/opcmon $monname=1
else
/usr/lpp/OV/bin/opcmon $monname=0
fi
exit 0
Debug output :-
bhau + monname=SAP_WEBDISP_Process_Monitor
+ + ps -ef
+ wc -l
+ grep wd.sap*
+ grep -v grep
NUM_PROC= 1
+ echo 1
1
+ + echo 1
NUM_PROC=1
+ [[ 1 -gt 0 ]]
+ /usr/lpp/OV/bin/opcmon SAP_WEBDISP_Process_Monitor=1
+ exit 0
————————————–
I am just surprising, how this script is evaluating the PS command. Help me if i am doing something wrong or can be possible in other way to capture my requirement.
Thanks GD
Hi Norman,
Please go through this chapter :
Regular Expressions in Grep Command with 10 Examples – Part I
Assuming that your file name is file1.txt. PLease provide the following command
grep -e “4\|6” file1.txt
HI
I HAVE A FILE LIKE
123AAAA1956 255
123AAAA1976 255
123AAAA1980 255
I WANT TO EXTRACT FULL DATA (FULL LINE) FROM THE ABOVE FILE WHICH IS LESS THAN 1978 STARTING FROM 8th POSITION TO 11th POSITION. I WANT TO MEAN THAT AFTER GIVING COMMAND THE OUTPUT WILL BE
123AAAA1956 255
123AAAA1976 255
CAN IT BE POSSIBLE WITH GREP COMMAND ?
ANY HELP FROM ANY BODY IS HIGHLY APPRECIABLE.
What is the command to display only the lines of a file with exactly 5 characters?
Great Article!!
Hi i have a query to find out from a table field called ‘design ation ‘, In the designation column many attributes are there likes Hr, Programmer, Trainee Programmer, Soft Programmer and Admin.
but I want to find out only Programmer not Trainee Programmer nor Soft Programmer nor others
How can i do using greep command please help me or else send me in my mail
Thanks for this. I’ve always used grep half assedly but his has given me a better understanding with the incremental practical examples.
How to get the values of applications from the below json object. I tried with below command , but it does not working
grep -iw ‘applications.?’
JSON Obejct:
{
“id”: “145ert678fa9”,
“aliasName”: null,
“applications”: [
“APPLICATIONS_1”,
“APPLICATIONS_2”,
“APPLICATIONS_3”
],
“businessId”: “270871”,
“vendorName”: “Testing for applicaitons”,
“availability”: “ACTIVE”,
“code”: “CN”,
“countryName”: “India”,
“updatedId”: null,
“emailAddress”: null,
“faxNumber”: null,
“latitude”: null,
“legalizationId”: null,
“actualCompanyId”: “e254wtr543”
}
I want to use grep command in my script
if $COMMAND | grep -q 'abcd'; then
echo "true"
fi
However -q option does not works in SunOS. How to do it in sunOS. Same is working fine on linux. I went through manual of this on SunOS bit didn't worked. Getting broken pipe error.
SunOS version:
SunOS hostname 5.10 Generic_150400-26 sun4v sparc SUNW,SPARC-Enterprise-T5220
$ grep -l this demo_*
demo_file
demo_file1
in the above example you have shown, can you please let me know what is “this” ?
As the syntax for grep is:
grep
Hence, “this” in above example is pattern or file name or something else ?
Please help.
Sujesh
Try this
grep ^…..$
good
like it …….
I often use grep . * to print content of some small files with name before it (especially useful in sysfs /sys/ tree – cat path/* just print bulk of data, but not which file have which data).
For example:
grep . /sys/class/thermal/*/temp
/sys/class/thermal/thermal_zone0/temp:54000
/sys/class/thermal/thermal_zone1/temp:54000
(printed current CPU cores temperature on my machine)
Another example:
grep . /sys/class/thermal/thermal_zone0/* 2>/dev/null
/sys/class/thermal/thermal_zone0/cdev0_trip_point:1
/sys/class/thermal/thermal_zone0/cdev0_weight:0
/sys/class/thermal/thermal_zone0/cdev1_trip_point:1
/sys/class/thermal/thermal_zone0/cdev1_weight:0
/sys/class/thermal/thermal_zone0/mode:enabled
/sys/class/thermal/thermal_zone0/policy:step_wise
/sys/class/thermal/thermal_zone0/temp:50000
/sys/class/thermal/thermal_zone0/trip_point_0_temp:98000
/sys/class/thermal/thermal_zone0/trip_point_0_type:critical
/sys/class/thermal/thermal_zone0/trip_point_1_temp:95000
/sys/class/thermal/thermal_zone0/trip_point_1_type:passive
/sys/class/thermal/thermal_zone0/type:acpitz
(printed thermal zone 0 props on my machine).
Output of this examples are much more eyecandy with grep –color=auto option enabled.
Thanks for your very useful tips. Appreciate it!
Hi All,
I need some help. Can we grep only unique items of a specific word from a file.
Ex If we grep on ERROR , we want to it to display only one error of each type
need Help to build the following script. Can anyone help ASAP?
Move_httpd_conf_modified_TO-httpd.conf
• Stop apache
• cd /etc/httpd/conf
• copy httpd.conf.modified to httpd.conf
• check ps –ef | grep apache
• check ipcs | grep apache
• no proses is running
• start apachectl start
2) Move_httpd_conf_orig_TO_httpd_conf
• Stop apache apachectl stop
• cd /etc/httpd/conf
• copy httpd.modified to httpd.conf
• check ps –ef | grep apache
• check ipcs | grep apache
• no proses is running
• start apachectl start
Thanks for your very useful tips. Appreciate it
how to check process is restarted or not?
Under step 4 you said
“This is a very powerful feature, if you can use use regular expression effectively.”
Did you mean to repeat the word use twice? I don’t quite get the meaning.
Very Informative…Was of a great help