Exact match grep

I need grep to match exactly in the list of results from the ls .

For example, if I ls directory and here are the results:

 system sys sbin proc init.rc init.mahimahi.rc init.goldfish.rc init 

I would like to grep see if a file named "init" exists. I need grep to return only one result. There is only one file in the list called "init".


I am performing this operation on an Android device. So here is the complete command:

 adb shell ls / | grep -E "^init$" 

I need to check for the existence of a directory on an Android device, and then perform an action if the directory exists.

I did this before using find in the script package, but I need to do this on linux using bash , and I want an exact match. This will avoid the problem if there is another directory or file containing the line I'm looking for.


I tried the sentences in the following links, but they all do not return the result when I give "init" as a parameter.

how-to-grep-the-exact-match

match-exact-word-using-grep

+2
source share
4 answers

Assuming the ls file has nothing to do with the file system (so you can't use the file system instead), grep '^init$' should do the trick.


xxd:

 00000a0: 2e67 6f6c 6466 6973 682e 7263 0d0a 696e .goldfish.rc..in 00000b0: 6974 0d0a 6465 6661 756c 742e 7072 6f70 it..default.prop 

based on this hexdump, I would suggest to enable it in unix style first:

 adb shell ls /|tr -d '\015'|grep '^init$' 
+4
source

To get an exact match, you must activate regular expressions with the -E option and use the beginning of lines and the end of line characters:

 grep -E "^init$" 
0
source

Are there any problems with grep ? What about awk ?

 ls | awk '$1 == "init"' 
0
source

The question is, which shell (device or your computer) do you want to make the shell extension / grepping / etc?

If you want your device to perform processing, the command should be

 adb shell "ls / | grep ^init$" 

If you want your computer to complete the task, the command will be

 adb shell "ls /" | tr -d '\r' | grep ^init$ 

But then again, like many others, when you know the exact file name - just check if it exists, there is no need for grepping

 adb shell "[ -f '/init' ] && echo 'found'" 
0
source

Source: https://habr.com/ru/post/1416184/


All Articles