You are on page 1of 25
sna 16 Practical Grep Command Examples In Linux! UNIX THE GEEK STUFF Linux | DB | Open Source | Web Home About Free eBook Axtchives Best ofthe Blog Contact 15 Practical Grep Command Examples In Linux / UNIX athiyaMoorthy on March 26, 2009 8 Lee | 58 Photo courtesy of Alexie’ ‘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 finctionality. Earlier we discussed 15 practical examples for Linux find command, Linux command line history and mysgladmin command, In this article let us review 15 practical examples of Linux grep command that will be very usefil to both newbies and experts. wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 128 ome 415 Practical Grep Gommans First create the following demo_fite that will be used in the examples below to demonstrate grep command, amples in Linux UNIX $ cat demo file THIS LINE 18 THE 1ST UPPER Gi this line is the ist lower « This Line Has All Zts First Character Of The Word With Uj Two lines ai L And this is the last line 1. Search for the given string in a single file The basic usage of grep command i to search for a specific string inthe specified fle as shown below. syntax: grep "literal_string" filename $ grep "this" demo file this line is the lst lower case 14 Two lines above this line is em 2. Checking for the given string in multiple files. Syntax: grep "string" FILE_PATTERN This is alo a basic usage of grep command, For this example, let us copy the demo_file to demo_file1. The grep output will alo include the fle name in front of the line that matched the specific pattem as shown below. When the Linux shell sees the meta character, it does the expansion and gives all the files as input to grep, 3 cp demo file demo filel is the ist lower case line in e:Two lines above this line is empty letAnd this is the last line s line is the lst lower case line in Two lines above this line is empty And this is the last line. 3. Case insensitive search using grep -i synta: grep 4 "string" FILE This is alo 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. ru NE this line is the lst lower case line 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 mtax wn tnegeekstul.com/2008/08/15-practical-unicgrep-commanc-examples! 2128 sna 16 Practical Grep Command Examples In Linux! UNIX grep “REG filename This is a very powerfil feature, ifyou can use use regular expression effectively. Inthe following example, it searches forall the pattern that starts with “lines” and ends with “empty” with anything in-between. ie To search “lines{anything in-betweenJempty” in the demo_fik. 3 grep Two lines above ty" deno_file 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 Ifyou 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 itis searching for “is”. When you search for option it will show out “is”, “his”, “this” and everything which has the substring “is”. ”, without any IS THE 1ST UPPER CASE LINE IN THIS FILE. is the ist lower case n this file. Has All its First Character Of The Word With Upper Case Two lines above g line is empty. And this is the last line The following example is the WORD grep where itis 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" deno THIS LINE I$ THE 1ST UPPER CASE LINE IN THIS F- this line is the ist lower case line in this file Two lines above And this is is empty. last line. 6. Displa ing lines before/after/around the match using grep -A, -B and -C ‘When doing a grep on a huge fle it may be usefil 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, 8 cat demo_text 4. Vim Word Navigation wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 3125 arn 16 Practical Grep Command Examples in Linux / UNIX You may want te do several navigation in relation to the words, such as: - go to the end of the current word. - go to the end of the current WORD. go to the previous (before) word. = go to the previous (before) WORD go to the next word. W- go to the next WORD. wowe 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 NORD and word * 192,168.1.1 - single WORD * 192,168.1.1 - seven words 6.1 Display N ines after match ~A is the option which prints the specified N lines affer the match as shown below. synta: grep -A "string" PILENAME 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 NORD and word * 192,168.11 - single WORD * 192.168.1.1 - seven words. 6.2 Display N lines before match Bis the option which prints the specified N lines before the match, synta: grep -B "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.11 - 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 & afler) of match, $ grep -C 2 "Example" deno_text word - word consists of a Sequence of letters, digits and underscores. Example to show the difference between WORD and word wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 425, sna 16 Practical Grep Command Examples In Linux! UNIX * 192,168.11 - single WoRD 7. Highlighting the search u: g GREP_OPTIONS ‘As grep prints out lines from the file by the pattem / string you had given, ‘matches the line, then you need to follow the following way. f you wanted itto highlight which part ‘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_OPTT OLOR="10) $ grep this line is the lst lower case line in this file Two lines above this line is empty. And this is he 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/pattem, use the option -v as shown below. This example will display all the lines that did not match the word “go”. 8 grep -v "go" demo_text 4. Vim Word Navigat 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 und Exanple to show and word * 192,168.11 - single WORD * 192,168.11 - seven wo 10. display the lines which does not matches all the given pattern. syntax grep -v -e “pattera" -e "pattern" $ cat test-file.txt wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 5125 sna 16 Practical Grep Command Examples In Linux! UNIX 11. Counting the number of matches using grep -¢ ‘When you want to count that how many lines matches the given pattern’string, then use the option -c. syntax: grep -c "pattern" filenane $ grep -c "go" demo_text ‘When you want do find out how many lines that does not match the pattem grep -v -c this demo_file 12. Display only the file names which matches the given pattern using grep -1 Ifyou want the grep to show out only the file names which matched the given pattem, use the 1 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 patter, will be very handy when you try to find some notes in your whole directory structure, 9 grep -1 this demo_* 13. Show only the matched string By default grep will show the line which matches the given pattem/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 usefil when you give the string straight forward. But it becomes very useful when you sive a regex pattem and trying to see what it matches $ grep -o “is.*line" demo, is line is the 1st 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” £: wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 6125 sna 16 Practical Grep Command Examples In Linux! UNIX Note: The output of the grep command above is not the position in the line, its byte offset of the whole fie 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 the end of the current word. the end of current WORD. the previous (before) word the previous (before) WORD. the next word 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 I © Search in a *.b22 file using bzgrep, and *.gz file using zerep. Awesome Linux Articles Following are few awesome 15 examples articles that you might find helpful. © Linux Crontab: 15 Awesome Cron Job Examples © Mommy, | found it! — 15 Practical Linux Find Command Examples @ 15 Examples To Master Linux Commend Line History © Unix LS Command: 15 Practical Examples 38 ue [58] @ Share Comment If you enjoyed this article, you might also like... 1 Li ss Tutorials © Awk Int nn — 7 Awk Print Exan 2. 50 Most Frequently Used Linux Commands (With * Advanced Sed Substitution Examples Examples} © 8 Essential Editor N: mn 3. Top 25 Best Linux Performance Monitoring and Fundamentals Debugging Tools © 25 Most Frequently Used Linux IPTal 4. Mommy, I found it! — 15 Practical Linux Find Rules Examples Command Examples eT charge PuTTY with 12 Ps ful Add- 5. Linux 101 Hacks 2nd Edition eBook ES Ons wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 18 arn 16 Practical Grep Command Examples in Linux / UNIX Bash 101 Hacks . ccosmsnat, | [Sed & Awk Vim 101 Hacks 101 HACKS Pc rp Soe IG ‘Tags: File Search Utility, Grep Command, Highlight Search Output, Linux Full-Text Searching, Linux Grep, Command, Search File Content, Search Multiple Files {75 comments... read them below or add one } 1 Joao Trindade March 28, 2009 at 3:54 am You have a small gltch: >> 4, Match regular expression in files using grep =i Don’t you mean: 4, Match regular expression in fles using grep -e ‘The rest of the post is great. 2 Ramesh March 29, 2009 at 12:16 am Joao, Thanks for pointing it out. Ihave corrected it. Also, we can do REGEX without the option -e as shown in the example #4. From Man Pages: SYNOPSIS grep [options] PATTERN [FILE...] grep [options] [-e PATTERN | -f FILE] [FILE...] ~e PATTERN, ~-regexp=2ATTERN Use PATTERN as the pattern; useful to protect patterns beginning with -. 3 dragon March 31, 2009 at 1126 pm Hi FYI, tip 14 will be 23 83 on Ubuntu system. (including the \n character I guess 4 Ramesh March 31, 2009 at 11:44 pm wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! ars, one 15 Practical Grep Command Examples In Linx! UNIX Dragon, ‘Thanks for pointing it out, I’ve corrected it 5 Francesco Talamona April 26, 2009 at 2:48 am | find very usefil the following command, when you have to deal with a very lengthy configuration file full of comments: grep -v-E ‘A\#))S? fete/squid/squid. conf Itskips 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 fl. BTW interesting topies, great posts. 6 albar May 7, 2009 at 7:51 pm help me how to bzgrep :*C02 but °C is count as one special character, in this word: datal*CO2data2 thank's 7 Ramesh Natarajan May 8, 2009 at 5:51 pm @Franceseo 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, itis an excellent idea to hide them in the grep output with your examples, 8 sasikala May 11, 2009 at 9:41 pm @albar, try like this grep C02" 9 albar May 12, 2009 at 1:18 am @saskala , ido have try that too, but still got nothing, but it works when “ and C count as two character thank's 10 SathiyaMoorthy May 12, 2009 at 4:33 am @albar ‘You should type *C as ctr-v + etre in grep as single character as $ grep *C02 file wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 9125 ome 15 Practical Gep Command Examples in Linux UNIX Dont escape, dont type it as * C as two characters. Hope this helps. LL abbar May 12, 2009 at 8:59 pm @sathiya, god bless wall it work's thanks 12 Manish Patel May 21, 2009 at 7:00 pm Hi Lam trying to exclude the last word of ll the line like syne.php, uploads.php, backup-php File text include as below Jast/home/htdocs/drag-and-drop/htdocs.php Just/home/fhtdoes/sms/publish’pages/syne. php Jast/home/htdocs/track/backup.php ust/home/htdocs/smstest/smstest.php Jast/home/htdocs/uploads.php Just/home/htdoes/017/backup-php How can [ 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 13 Francesco Talamona May 21, 2009 at 10:36 pm. ‘Are you restricted to sed or awk? 1) dimame ‘/ust/home/htdoes/drag-and-drop/htdoes. php’ Jastfhome/htdocs/drag-and-drop 2) rename does what you want 114 Manish Patel May 24, 2009 at 6:55 pm 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 fle names ending at the line should be removed, So the final file contents should look like this cat filecontenet.txt just/home/htdocs/drag-and-drop/ Jast/home!fhtdoes/sms/publish/pages! Just/home/htdoes/track! Jast/home/htdocs/smstest! wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 10125 sna 16 Practical Grep Command Examples In Linux! UNIX Just/bome/htdocs/ Just/home/htdocs/ | think rename would not help here in editing file contents. ‘Thank you Manish 15 SathiyaMoorthy May 24, 2009 at 11:43 pm rev fiecontenet.txt | cut -d°/" -2- | rev rev filecontenet.txt > reverses the fle and pipes to cut command. cut -d'/’ -12-—> cuts off the first field ( cuts off last field, as it is reversed ). rev prints the output given order. 16 POBOT May 26, 2009 at 11:36 pm Manish, believe you're looking for the following sed -c ‘s/.php$/' filecontenet.txt 17 POBOT May 26, 2009 at 11:39 pm Sorry, didn't read your requirement carefully. Try this: sed -e ‘s/V[V]*.php$/V/' filecontenet.txt 18 Manish Patel June 5, 2009 at 5:31 pm Hi ‘Thank you to Sathiya Moorthy and POBOT. Both solution worked very nicely for me. POBOT can you explain how your command works for each defined option ’s/V[*/|*.phpS\" ‘Thank you Manish 19 mano June 10, 2009 at 3:00 am ‘The above info on grep is really great. I want to search fora 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, 20 SathiyaMoorthy June 18, 2009 at 10:49 pm @mano More than using grep for this requirement, you can use sed which is: sed -i's/.*abe.*/S&/" * wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 11125 sna 15 Practical Gep Command Examples in Linux UNIX i edit the input fil sill: substitute the matched pattem with the replacement string. J.tabe.*/ : match the string abe $4 : Replace with $ followed by matched string, * :allthe files in the current directory. ‘This is one way of satisfying your requirement, there may be other efficient ways Hope this helps. 21 mano June 19, 2009 at 12:17 am Hi SathiaMoorthy, Thank u so much. it works fine. If need to search for files in all subdirectories, how should this “sed” command modified? ‘Thanks in advance. mano 22 SathiyaMoorthy June 27, 2009 at 12:05 am @mano Modification in sed command is not needed. To search for all files in the subdirectory. find . -type £ Execute the command on all those files with -exec. find . -type f-exec sed -i‘s/.*abe.*/#&" {} \s 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. 23 Vidya July 1, 2009 at 2:59 am 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 -¢ enterprise” fiom 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” 24 SathiyaMoorthy July 1, 2009 at 5:58 am @Vidhya $ grep -o -E—“-g\wt -c \wt” FILENAME “8 gateway -e enterprise wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 12s ome 15 Practical Gep Command Examples in Linux UNIX Explanation of the above command., ~o : only matching ( point 13. ) -E : extended regexp —:indicate end of options Wwe : word 25 Vidya July 1, 2009 at 9:00 am Hi Sathiya, Its not working It says grep: legal option —o grep: illegal option — Usage: grep -hblensviw pattern fle... Lam working on Solaris and setting shell as bash. 26 Amit Agarwal September 21, 2009 at 6:18 am gzep version on solaris is litle 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. 27 learner October 7, 2009 at 531 am Hi, How to use grep to find lines containing mutiple strings ex: line I:Today is oct 7, wednesday. not 8th line2: This is not summer line3: when is summer? I want to retum line2 containing strings “not” and “summer” both. ‘Thank You, 28 SathiyaMoorthy October 7, 2009 at 10:41 am @learner There are several ways possible, use the one which you find as appropriate 9 grep "not. *summer' line2: This is not summer $ grep "not" file | grep line2: This is not summer 29 learner October 7, 2009 at 10:56 pm @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 ‘string] wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 13925 sna 15 Practical Grep Command Examples In Linx! UNIX string? string3 strings stringn’ filename which retums single occurrence of something like either string] ,string2,.. stringn or all... what i wanted was only string! and string? 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. 30 Ashish December 1, 2009 at 4:07 pm Hi, need to sthing lke this Thave a fle containing 400 domaintd values seprated by new line ex. domain.txt domain! domain2 domains... Thave a script that takes each domain and calls an api that returns me an xm. like this for each domain vall domain} val vaB valt XXX vall now i want to spit out the domain name in a file that does not matches domainid value XXX. how can ido it using grep TIA 31 Ashish December 1, 2009 at 4:16 pm Hi, Ineed to sthing lke this Thave a file containing 400 domainld values seprated by new line ex, domaintxt domain! domain2 domains... Thave a script that takes each domain and calls an api that retums me an xm. like this for each domain vall wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 14125 ama 415 Practical Grep Gommand Examples In Linux/UNIX domain! vall val3 val4 XXX vall now i want to spit out the domain name in a file that does not matches domainid value XXX. how can ido it using grep TIA 32 Varun December 17, 2009 at 7:16 am 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 of this grep available for Sola 33 Jawn Hewz December 21, 2009 at 7:54 pm Does the -b (byte offiet) work when greping binary files? I do not get an offSet retuned when I grep a binary fie, but I do when using a text file. am using grep under Cygwin. 34 fety January 11, 2010 at 3:32 am thanks very much for this tutorial. it is very helpful. 35 eMancu January 24, 2010 at 12:49 pm. Awsome tutorial! T'mreading all your blog, its amazing! 36 Raghu Baba January 30, 2010 at 4:44 am Hai. I want to Parse my file . Word to Excel . so tell me some grep & cut commands. 31 Jeff Floyd February 1, 2010 at 6:54 pm ‘Whats the difference between $ grep -c ill memo and $ grep -n ill memo? 38 jocg February 4, 2010 at 3:57 am hi i got | problm...how can ifind a numbers like 99,000,000.95 in my server database using unix command, q 39 abhishek February 21, 2010 at 4:31 am content was very usefil wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 19125 sna 16 Practical Grep Command Examples In Linux! UNIX 40 Anonymous March 8, 2010 at 4:26 am 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 Just/home/htdocs/drag-and-drop/ just/home//htdocs/sms/publish/pages! Jast/home/htdocs/track! just/home/htdocs/smstest! Just/home/htdocs! justfhome/htdocs! | think rename would not help here in editing file contents. for this question , awk really helpful with single line command ¢g0 to the current directory b-l| grep -v°d | awk {print $9}” > new.txt $9 — is the last fled which is filename only when w list with option Is -1, new.txt contains only the filenames which you wnated to fiter out 1 skipper March 26, 2010 at 5:54 am hice article 42 VIKAS April 4, 2010 at 723 pm Excellent stuff, just loved grep -A,B,C options and grep -0 “Soon. *yyyy” kinda commands. This will help me a lot, Tused awk more in my shell scripts, But Thave got a new ffiend “grep” for some selective printing @ 43 Sam April 17, 2010 at 3:35 am T 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 retum the number lines that matched ill in memo. ‘grep -nretum the matched lines with line-number as prefix. 44 Chong April 20, 2010 at 3:05 am how to grep a statement contain” fom file at the same time to match the first character too. ‘example the statement in filename profil. txt = “Mary stay at uttana*istana with her grandmum” current grep statement > wu tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 16125 ama 45 Practical Grep Command Examples In Linux / UNIX 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? 45 vm April 30, 2010 at 8:24 pm In bash script without using perl, how ican grep a number froma fil ifthere exists a number greater than 80 in that file, 46 palash June 13, 2010 at 12:14 pm grep -c “pattem” fname returns the number of lies that matches the pattern, even if he pattem occurred for more than one time in any line. Is there any option to know how many times the pattern matched in a file? 47 mathan June 20, 2010 at 10:21 am Hi, Tam new to linux... can you tell me how to exit from grep command. mistakenly itype grep filename Bul it’s nothing shown... pls looking for quick reply... 48 SathiyaMoorthy July 4, 2010 at 720 am @mathan ‘There is nothing lke 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. 49 Ross Hugget! September 16, 2010 at 5:04 am e article, Thanks, N 50 ec October 6, 2010 at 6:14 pm Hito all, 1 just started to learn tinux 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? tried any combination of grep and not the result which I am looking for 51 Lou February 24, 2011 at 1:16 pm Is there a way to grep for a word on ina file and return that line plus the next? 52 Francesco Talamona February 26, 2011 at 333 am @ Lou: wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 172s ome 15 Practical Gep Command Examples in Linux UNIX cat testfile. txt first line matching line following line ending line ‘grep matching -B 1 testile.txt first line ‘matching line 53 abhishek kumar April 19, 2011 at 12:53 pm really to nice and too simple to understand, thats great thank you 54 Nikita April21, 2011 at 12:06 pm 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-2A-Z][A-Za-7])’ 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 ffom 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! ‘55 Francesco Talamona April 22, 2011 at 12:44 pm, @Nikita: ‘One step is enough: egrep “\([a-zA-Z]{2}\)’ file ‘56 suprabhat April27, 2011 at 326 am How to display al ines that have less than 9 character ina file 57 Paul May 16, 2011 at 3:09 pm I’'mnew to linux; was wondering what does \# after the grep command accomplish, as shown in the example below? grep ‘i input*.txt | awk * {print $4’ | sort | unig > output.txt thank you ‘58 Dinesh May 17, 2011 at 4:03 pm wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 16125 sna 15 Practical Gep Command Examples in Linux UNIX Fora given pate lke Fri Nov 26 16:04:52 2010 want to grep for all the lines in file having the above format. But [ 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 59 shyam May 29, 2011 at 10:45 pm ihave a doubt here itried to look at output of emd grep “(A-Z)’ file-txt this is showing all characters excluding capital letter ‘what does this command actually do 60 shivaraj Patil July 25, 2011 at 11:14 am Hl i have a file with this values 100 first ine 101 second line 101 102 102 109 now inced a script that can take two lines and find which is greatest G1 sudheer September 10, 2011 at 8:32 pm 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 mumbers 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 affer it, for example punctuation, What to tum in: Tum in three things: a. A file with the regular expression which can directly be used by grep (or awk) . 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 begining and the end of lies, sentences, ete. 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 (c.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 tum 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 wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 19125 ome 15 Practical Gep Command Examples in Linux UNIX make sure that you specify exactly what they are (e.g. if you use digit specify that that means 0, 1, 2, 3, 9.) 62 Dinesh September 22, 2011 at 12:43 pm Paul ‘grep \¥ input* txt | awk *{print $4}? | sort | unig > output.txt Since # is a special character,we are treating # as # by putting backslash infront of that, Noe Greap searches for pattem # ina list of file starting as input and nding a txt and then awk prints the 4th fied and sort is doing sorting the 4th field retums fiom awk and unis is doing unig operation. 63 Dinesh September 22, 2011 at 12:45 pm Shyam grep “[°A-Z)’ flext 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 .. 64 haydarekarrar December 23, 2011 at 4:29 am 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 Ist lower case line in this fie Two lines above this lin is empty. ‘And this isthe last line. 65 gotham January 22, 2012 at 432 am awesome, thanks a lot. 66 edward January 31, 2012 at 220 am For example my data is (fie.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 FOL -69.27 Luse grep as: grep -t 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 FOI ? IfI use grep - F’ *.ave, the first line will be taken also because of STF, Thanks for help. 67 shrikant February 14, 2012 at 10:23 am Thank you@ wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 20128 sna 16 Practical Grep Command Examples In Linux! UNIX 68 chinna February 19, 2012 at 8:48 am here my question is in a directory ihave 10 files.some files contains size in kb’s and some files contains size in mb’s.... want display the files only which fle size is more than | mb, could anybudy help to find answer for this question... 69 Anderson Venturini March 14, 2012 at 6:01 am Great post! It was very useful! thanks a lot! @ 20 Anonymous April 9, 2012 at 322 pm ‘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+detal forall ile sizes listed. ‘Then you can use “awk” to filter out files where $5 (Sth field) is over IMeg, like this: bins -1| awk ‘$5>=2°20" Ifyou only want file names, not ‘ls’ style list, then have awk give you that part of output: Pbin/s -1 | awk *S5>-2720 {print SNF}? 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 #4 comments ffom long contig files) grep -v-E *\#)S" lete/squid/squid. conf You may want to remove comments that do NOT start on the first char ofa line, and ‘sed’ is more usefil for that sed ‘s/#*Si//"[ ]*8/d” /ete/squid/squid.cont This will remove comments from each lin, 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 7 KHEE April 15, 2012 at 839 pm Hi expert, iam new to unix env, try to use certain command to help me generate 1 output file as below: ‘input file: A A10.203 0.8 B B06 0.80.9 Cc wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 21128 sna 16 Practical Grep Command Examples In Linux! UNIX C08 2.1 6.0 [just want to grep all A B C only, where want to skip the line which have the number together. And my output file pattem is A B C D...ete (A, B,C all are a word). ‘mean i want first,second line, and skip 3rd & 4th lines, thanks for help. 12 krishna April 20, 2012 at 9:15 pm How do you find using regular expression, characters beginning with and ending with any characters. In AXyz12231 1 Xyslasd22344ssaa Aklsssx@sdddfit4=sadsss kaaAASds How do we get the characters “slas” out that begins with “1 LXy” and ends with “223” in UNIX using regular expression? echo $MSG | grep -0 *(2<=11Xy).+(?=d223) 73 bala May 10, 2012 at 9:12 am @krishna, echo SMSG | grep -0 11Xy.#d223 74 guru May 22, 2012 at 11:52 am ined 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 fine 5 mitchell fox May 24, 2012 at 7:45 am T know this isa simpk: grep or grep/sed question: Thave 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 Leave a Comment E-mail Website wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 22s arn 16 Practical Grep Command Examples in Linux / UNIX Previous post: Mergecap and Tshark: Merge Packet Dumps and Analyze Network Traffic Next post: 4 Ways to Identify Who is Logged-In on Your Linux System © Sign up for our free email newsletter [you@address.com Sign Up | ®aRss & Twitter Facebook Search * EBOOKS Prorttacks (|) G Practical Examples to Build a Strong Foundation in Linux Bash 101 Hacks Take Control of Your Bash Command Line and Shell Scripting Sed & Awk 101 Hacks 7 Enhance Your UNIX / Linux Life with Sed and Awk wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 2315 sna 16 Practical Grep Command Examples n Linux UNIX 101 Hacks Vim Practical Examples for Becoming Fast and Productive in Vim Editor Monitor Everything, Be Proactive, and Sleep Well * POPULAR POSTS RA Essential Linux Books To Enrich Your Br Library 50 UNIX / Linux Sysadmin Tutorials 50 Most Frequently Us IX / Linux Commane th Examples How To Be Productive and Get Things Done Using GID 3 To Do When you are B x er Linux Directory Structure (File System Structure) Explained with Examples Li ntab: 15 Awesome Cron Job Exar Get a Grip on the Grep! — 15 Practical Grep Command Examples LS Command: 15 Practical Ex; 15 Examples To Master Linux Command Line History ‘Top 10 Open Source Bug Track: m Viand Vim Macro Tutorial: How To Record and Play Mi 1 it! -- 15 Practical Linux Find Command Example: 15 Awesome Gmail Tips and Tricks 15 Awesome Gi ch Tips and Trick: RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams Can You Top This? 15 Practical Linux Top Command Examples ‘Top 5 Best System Monitoring Tools ‘Top 5 Best Linux OS Distributions How To Monitor Remote Linux Host using Nagios 3,0 Awk Introduction Tutorial — 7 Awk Print Exan How to Backup Linux? 15 rsyne Command Examples ‘The Ultimate W get Di Guide With 15 Awesome Exampk ‘Top 5 Best Linux Text Editors Packet Analyzer: 15 TCPDUMP Command Examples ‘The Ultimate Bash Array Tutorial with 15 Examples 3 Steps to Perform SSH Login Without Passwor¢ sh-keygen & ssh-copy- Unix Sed Tutorial: Advanced Sed Substitution Examples JNIX / Linux: 10 Netstat Command Exai ‘The Ultimate Guide for Creating Strong Passwords 6 Steps to Secure Your Home Wireless Network Turbocharge PuTTY with 12 Powerful Add-Ons wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 24128 sna 16 Practical Grep Command Examples In Linux! UNIX « About The Geek Stuff My name is Ramesh Natarajan. I wil be posting instruction guides, how-to, troubleshooting tips and tricks on Linux, database, hardware, security and web, My focus is to write articles that will either teach you or help you resolve a problem. Read more about Ramesh Natarajan and the blog, * Support Us Support this blog by purchasing one of my ebooks. Bash 101 Hacks eBook Sed and Awk 101 Hacks eBook Vim 101 Hacks eBook jagios Core 3 eBook * Contact Us Email Me : Use this Contact Form to get in touch me with your comments, questions or suggestions about this site, You can also simply drop me a line to say hello! Follow us on Twitter Become a fin on Facebook ‘Copyright © 2008-2012 Ramesh Natarajan. All rights reserved | Terms of Servi wn tnegeokstul.com/2008/08/15-pracical-unicgrep-commanc-examples! 25125

You might also like