Small shell tools for text editing

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Searching with grep

With grep , you can search through text files or data streams in pipes. Numerous options are available in shell scripts or by direct calls.

Table 5 shows a selection. The grep search patterns can also be regular expressions (regex). Some of the examples may have multiple solutions! You can use special designations in search patterns for character classes (Table 6). Note the character classes in double brackets ('[[:alpha:]]' ). You can basically use all options within a pipe, as long as they don't relate to files or directories (-l and -L ).

Table 5
Table 6

For shell programming, the grep return values are important: 0 means found and 1 means an error; other errors are acknowledged with exit code 2. For testing purposes and as a short experimental platform, you can use the script in Listing 1. You can cancel the input using Ctrl+C. Figure 5 shows the outcome for both, and Table 7 shows some additional possibilities.

Table 7

Listing 1

01 #! /bin/sh
02 while true;
03 do
04 echo -n "Enter search term: ";read search_term
05 cat a.txt | grep -q $search_term
06 return_value=$(echo $?)
07 if [ $return_value -eq 0 ];
08   then
09        echo "Search term found."
10 elif [ $return_value -eq 1 ];
11   then
12        echo "No match!"
13 fi
14 done
Figure 5: Output of


A convenient program for scanning and searching is less . This goes for text files as well as in pipes. For example, you can do the following:



... | less

Table 8 shows the most important options. How you eventually work with the program depends largely on the terminal characteristics, which is particularly true of navigation in text. You can quit the program using Ctrl+Q.

Table 8

To navigate around the files that you browse with most distributions, you can simply use the arrow keys or use the keys described in Table 9.

Table 9

If you're scanning through a text file with less , you can press v to open it in an editor. If you do so while less is working on a pipe, an error message appears. Entering /[SEARCHTERM] will begin the search. The results are highlighted in reverse video on the screen.

Buy this article as PDF

Express-Checkout as PDF

Pages: 1

Price $0.99
(incl. VAT)

Buy Ubuntu User

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content