*NIX Tricks

[cli] Selectively break a string into pieces and display in new lines

Posted in cli, unix by kousik on January 14, 2010

Display each different part of a string separated by a character, say colon (:), in new lines:

Using echo:
$ echo -e ${PATH//:/\\n}

Using printf:
$ printf "%s\n" ${PATH//:/\/* }

Here we chose the system $PATH variable whose different parts are separated by colons.

Credit: Command-line-fu

[cli] Find out success status of a command in BASH/ CSH

Posted in bash, cli, csh by kousik on November 20, 2009

To know the return value of a command, in BASH run
$ echo $?
and in CSH/ TCSH run
$ echo $status
which will give you the return value (0 or 1) of the last command (the one issued just before the echo).

In both the shells, if the above spits out 0 (zero), it means the previous command was successfully completed, otherwise it’ll give rise to 1 (unsuccessful!) — quite contrary to our concept of 0 being false and 1 being true, eh!

Credit: Oracle Spin.

[awk] Print selective columns and watch for changes

Posted in awk by kousik on September 26, 2009

Print columns 1, 5 and then 2, put a colon, and then print column 10 of a line that matches pattern from the file columns.txt:

$ awk '/pattern/ {print $1, $5, $2, ": ", $10}' columns.txt

.
Protecting the special meaning of the single quotes and curly braces
I came across this situation when I was trying to watch the above command as well as two other commands (say, command1 and command2) at the same time. The correct way to do that is by properly protecting the meaning of the special characters in the above awk invocation:

$ watch -d -n 20 "command1; command2; awk '"'/pattern/ {print $1, $5, $2, ": ", $10}'"' columns.txt"

.
N.B. The “-d”flag highlights the changes, whereas the “-n 20” flag causes the above to watch every 20 seconds.

Just for the heck of it, let me put the full command that I was actually using:

$ watch -d -n 20 "ps aux | grep -i columbus | grep -v grep && echo; tail WORK/ciudgsm && echo && grep bond output.log | tail -13 && echo && awk '"'/state # 1/ {print $3,$4,$5,": ", $10}'"' output.log && echo; awk '"'/state # 2/ {print $3,$4,$5,": ", $10}'"' output.log && head curr_iter"

(suggestions for making the above shorter, other than by aliasing, are most welcome!).

Reference: here.

Tagged with: , , , , , , , , , , ,
Follow

Get every new post delivered to your Inbox.