252 CHAPTER 15 (Sex offenders web site) WORKING WITH TEXT FILES

252 CHAPTER 15 WORKING WITH TEXT FILES Figure 15-5. grep is a powerful tool that can search for text within files. Tip You might never choose to use grep for searching for text within files, but it can prove very handy when used to search through the output of other commands. This is done by piping the output from one command to another, as explained in Chapter 17. Using Regular Expressions The true power of grep is achieved by the use of search patterns known as regular expressions, or regexes for short. Put simply, regexes allow you to be vague rather than specific when searching, meaning that grep (and many similar tools that use the system of regexes, such as the find command discussed in Chapter 14) will return more results. For example, you can specify a selection or series of characters (called a string in regex terminology) that might appear in a word or phrase you re searching for. This can be useful if you re looking for a word that might be spelled differently from how you anticipate, for example. The most basic form of regex is the bracket expansion. This is where additional search terms are enclosed in square brackets within a search string. For example, suppose you want to find a file that refers to several drafts of a document you ve been working on. The files are called myfile_1draft.doc, myfile_2draft.doc, and so on. To find any document that mentions these files, you could type this: grep ‘myfile_[1-9]draft.doc’ * The use of square brackets tells grepto fill in details within the search string based on what s inside the square brackets. In this case, 1-9 means that all the numbers from one to nine should be applied to the search string. It s as if you ve told grep to search for myfile_1draft.doc, and

Leave a Reply