Useful Unix Commands and Tips - Part 2
This is in continuation to the first part in the series. Let us discuss grep and lsof in part 2:
grep:
1) Case insensitive search:
grep -i "string" FILE
2) Checking for full words, not for sub-strings using grep -w
grep -w "serachword" file
3) Displaying lines before/after/around the match using grep -A, -B and -C. This is very useful if you want to see lines around search string:
i) grep -A <N> "string" FILENAME # display N lines after match:
ii) grep -B <N> "string" FILENAME # display N lines before match
iii) grep -C 2 "Example" demo_text # display N lines around match
4) Searching in all files recursively using grep -r
grep -r "ramesh" *
5) Invert match using grep -v
grep -v -e "pattern" -e "pattern"
6) Counting the number of matches using grep -c. There is no need to pipe the output to wc.
grep -c "pattern" filename
grep -v -c this demo_file (Count of lines not matching pattern)
7) Display only the file names which matches the given pattern using grep -l
grep -l <string> *
8) Show line number while displaying the output using grep -n
grep -n "go" demo_text
9) grep doesn’t support multiple string search. We need to use egrep.
egrep 'warning|error|critical' /var/log/messages
lsof:
1) To see all files opened by a process:
lsof -p <pid>
2) To list all tcp connections:
lsof -a -i4 -i6 -itcp
3) To find connections to a specific host:
lsof -i@hostname
4) Final all network connections when port on one side is known:
lsof -i :portNumber # Display all connections where one of the ports is known
lsof -i tcp:portNumber # Display all TCP connections where one of the port is portNumber
lsof -i udp:portNumber # Display all UDP connections where one of the port is portNumber
5) To find established connections:
lsof -i -sTCP:ESTABLISHED
6) Files opened by a user:
lsof -u ramesh
7) Files opened by users other than a particular user:
lsof -u ^ramesh
8) lsof can be used to find all resources interacting with it. Like users, processes, etc.
lsof /u01/data
Comments
Post a Comment