It is easy, flexible, very secure, updated, “free”, open source… and the list goes on however what makes me more happy on this little world *unix it is its flexibility.
The power
Let start with a simple command, like ps, which can show you a list of current process and its details.
ps -aux
Now, I would like to just shows the output lines which has usr on it. To do that I will use the output of ps -aux command as input to grep filter the data. On linux you can pass the output of a command to another by using a pipe. So we can redirect the last output as input to another one.
ps -aux | grep usr
Now we have the output from ps filtered by only lines which contains ‘usr’. But what if want only the process id’s. There is a program for that too, the cut.
ps -aux | grep usr | cut -d " " -f 8
This program cut is simple creating fields (-f) delimited (-d) by a space (” “) and I ask the program to pick the field 8, which is the process ids. But if you notice there is some lines without number. The next step is remove this lines without values. We can do it by using sed program.
ps -aux | grep usr | cut -d " " -f 8 | sed '/^$/d'
Now our output has only lines with numbers, sed program receives a simple regex and says delete this pattern. Nice but I just need those numbers ending with 2. We can grep again.
ps -aux | grep usr | cut -d " " -f 8 | sed '/^$/d' | grep $2
I also want to sum all this numbers and show on the screen the result. To achieve that we are gonna use awk program.
ps -aux | grep usr | cut -d " " -f 8 | sed '/^$/d' | grep $2 | awk '{ sum += $1; print "+" $1} END {print "_____" ; print sum}'
The first code (surrounded by brackets) will create a variable called sum and it also prints plus and each first argument passed to it. This first block will be called for every line we pass (processed by all the programs we did it) and it follows by END that will print a line and finally prints the sum of all this stuffs.
+1692
+1712
+1732
+1752
+1762
+1962
+2062
_____
12674
You can use programs connect them produce output that only one program can not do. PS: I know I could too all this with less programs/commands but the intend here was not teach linux/GNU programs it was show you how powerful can be linux.
Bonus round
You can put this output to a file just using the redirect to a file. ( > or >> to append)
ps -aux | grep usr | cut -d " " -f 8 | sed '/^$/d' | grep $2 | awk '{ sum += $1; print "+" $1} END {print "_____" ; print sum}' > file.txt
You must be logged in to post a comment.