Free php web host - 274 CHAPTER 17 COOL SHELL TRICKS and
Friday, November 30th, 2007274 CHAPTER 17 COOL SHELL TRICKS and then pipe the results to grep, which is able to search through text for a user-defined string (see Chapter 15): ls l | grep i ‘flower’ In this example, the shell runs the ls l command, and then passes the output to grep. The grepcommand then searches the output for the word flower (the i option tells it to ignore uppercase and lowercase). If grep finds any results, it will show them on your screen. The key point to remember is that grep is used here as it normally is at the command prompt. The only difference is that it s being passed input from a previous command, rather than being used on its own. You can pipe more than once on a command line. Suppose you know that the filename of the picture you want involves the words flower and daffodil, yet you re unsure of where they might fall in the filename. In this case, you could type the following: ls l | grep i flower | grep -i daffodil This will pass the result of the directory listing to the first grep, which will search the output for the word flower. The second pipe causes the output from grep to be passed to the second grep command, where it s then searched for the word daffodil. Any results are then displayed on your screen. Redirecting Output Redirecting is like piping, except that the output is passed to a file rather than to another command. Redirecting can also work the other way: the contents of a file can be passed to a command. If you wanted to create a file that contained a directory listing, you could type this: ls l > directorylisting.txt The angle bracket (>) between the commands tells BASH to direct the output of the ls l command into a file called directorylisting.txt. If a file with this name exists, it s overwritten with new data. If it doesn t exist, it s created from scratch. You can add data to an already existing file using two angle brackets: ls l >> directorylisting.txt This will append the result of the directory listing to the end of the file directorylisting.txt, although, once again, if the file doesn t exist, it will be created from scratch. Redirecting output can get very sophisticated and useful. Take a look at the following: cat myfile1.txt myfile2.txt > myfile3.txt As you learned in Chapter 15, the cat command joins two or more files together. If the command were used on its own without the redirection, it would cause BASH to print myfile1.txt on the screen, immediately followed by myfile2.txt. As far as BASH is concerned, it has joined myfile1.txtto myfile2.txt, and then sent them to standard output (the screen). By specifying a redirection, you have BASH send the output to a third file. Using cat with redirection is a handy way of combining two files.