Difference between revisions of "Grep"

From Linuxintro
imported>ThorstenStaerk
 
(4 intermediate revisions by one other user not shown)
Line 1: Line 1:
 +
grep is a [[command]] that reads strings and only outputs them if they ''match'' a ''pattern''. For example to show all lines in a file ''syslog'' that contain the string ''Nov'' call it like:
 +
grep "''Nov''" ''syslog''
 +
 +
<iframe width="90%" height="600" allowfullscreen frameborder="0" src="https://bubbl.us/NTcxNTA0MC8xMzA2MDQ3Ny82MDgyNzQ0ODUyYjUyZGQyN2ZlNmUyZjcyMzQ0ZDJlZg==-X?s=13060477&utm_source=page-embed&utm_medium=link"></iframe>
 +
 +
= Examples =
 
* Show all lines that do '''not''' contain blabla
 
* Show all lines that do '''not''' contain blabla
 
  grep -v blabla filename.txt
 
  grep -v blabla filename.txt
Line 14: Line 20:
 
* Match any character but blank
 
* Match any character but blank
 
  grep -E "L[^ ]nux"
 
  grep -E "L[^ ]nux"
Match Linux, Lanux, but not Lnux and not L nux
+
Matches Linux, Lanux, but not Lnux and not L nux
 +
 
 +
* Match any line starting with a character
 +
grep -E "U"
 +
Matches all lines starting with U
 +
 
 +
* Show all files containing ''content''
 +
grep -ir "''content''" *
 +
 
 +
= Usecases =
 +
 
 +
== Show all running processes ==
 +
 
 +
[[ps]] auxf | grep -E "^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +R"
  
 
= See also =
 
= See also =
 
* [[regex]]
 
* [[regex]]
 +
 +
[[Category:Command]]

Latest revision as of 17:57, 28 February 2022

grep is a command that reads strings and only outputs them if they match a pattern. For example to show all lines in a file syslog that contain the string Nov call it like:

grep "Nov" syslog

<iframe width="90%" height="600" allowfullscreen frameborder="0" src="https://bubbl.us/NTcxNTA0MC8xMzA2MDQ3Ny82MDgyNzQ0ODUyYjUyZGQyN2ZlNmUyZjcyMzQ0ZDJlZg==-X?s=13060477&utm_source=page-embed&utm_medium=link"></iframe>

Examples

  • Show all lines that do not contain blabla
grep -v blabla filename.txt
  • Match any character

With a dot (.) you can match any character

grep -E "L.nux"

Matches Linux, Lanux L nux, but not Lnux

  • Match all characters

With a .* you can match an arbitrary count of any character

grep -E "L.*nux"

Matches Linux, Liinux, Lanux, L nux and Lnux

  • Match any character but blank
grep -E "L[^ ]nux"

Matches Linux, Lanux, but not Lnux and not L nux

  • Match any line starting with a character
grep -E "U"

Matches all lines starting with U

  • Show all files containing content
grep -ir "content" *

Usecases

Show all running processes

ps auxf | grep -E "^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +R"

See also