Let's say I want to look for a line that has Apple or pie followed by cinnamon, then, I will be using the following: grep "apple\|pie" recipes.txt | grep "cinnamon" So in that case, you can use the grep command in the following syntax: grep "String1\|String2" File.txt | grep "String3" You may want to look for multiple strings with a condition like Sting1 or String2 must be followed by the String3. Look for string1 or string2 is followed by string3 So if I were to remove space from the above command, it will look for two possibilities: Applepie or Applecider. This will instruct grep to find a string that starts immediately after the other one. If you notice closely, every option placed inside the brackets () starts with the space as in the file, they must be separated by the space.īut if you want the continuous string that combines one or the other option, you can remove the space. Similarly, you can also add options such as apple followed by pie or cider as shown in the following command: grep -n "Apple\( pie\| cider\)" recipes.txt Here, I will be using the -n option which will notify the user of the line number if the grep finds the specified string: grep "String1\(String2\)" recipes.txtįor example, here, I want to find the Apple followed by the pie in the recipes.txt, so, I used the following command: grep -n "Apple\( pie\)" recipes.txtĪnd as you can see, it gave me the output from the specified conditions and it was the first line of the file. This is one of the most useful examples, in my opinion, as I often find myself in a situation where I have to look for a string followed by the other. Here, I've used the -n flag which will print the number of the line from where the keyword was found. So lets I want to look for "apple" or "pear" or "mango" from the fruits.txt, then, I will be using the following command: grep -E -n"apple|mango|pear" fruits.txt Similarly, you can use the -E flag to avoid using \ to separate different patterns: grep -E "String1|String2|String3" File.txt In the above snapshot, in the left window, I have used the cat command to print the file contents and in the right window, I have used the command that gave me the output with the specific requirement. So let's say you have to look for one or the other (either this or that situation) and in that case, you can use the grep command in the following manner: grep "String1\|String2" File.txtįor example, here, I want to look for the lines containing apple or orange in the fruits.txt file, then I will be using the following: grep "apple\|orange" fruits.txt Now, let's have a look at some practical examples. NOT ( -v): It is used when you want everything but not the output from the given pattern.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |