Thursday, June 25, 2009

few scripting tips.



How to get the last digits of a string e.g print 201 for string ua07app201?


#sed back reference: print the first match pattern enclosed by ( )
echo ua07app201 | sed 's/.*[^0-9]\([0-9]*\)$/\1/'

#Sed delete: Delete the longest match of non-digits char
echo 'ua07app201' | sed 's/.*[^0-9]//'

#Expr matching operator : Similar to sed back reference, without (), it returns the the number of matched chars.
expr ua07app201 : '.*[^0-9]\([0-9]*\)$'

#Awk: set non-digit as seperator, print the last filed $NF
echo 'ua07app201' | nawk -F'[^0-9]' '{print $NF}'

#Perl in command line mode
echo ua07app201 | perl -nle ' $_ =~m /(\d+$)/; print $1'
or the simplizied version
echo ua07app201|perl -nle'print/(\d+)$/'

#Parameter Substitution, delete the longest match of non-digits chars from beginning.
a='ua07app201';echo "${a##*[!0-9]}"


How to get path only from full path of a file?


#Parameter Substitution, delete the shortest match from end
$ var=/var/tmp/test.txt;echo ${var%/*}
/var/tmp


How to sort a string?


#one-liner to sort a string
$echo "s03 s08 s01" | tr '[:space:]' '\n' | sort -n | paste -s
s01     s03     s08

Monday, June 1, 2009

ctrl+A and ctrl+E key shortcuts can’t move cursor in bash.


ctrl+A and ctrl+E are mostly used key shortcuts to move cursor the start/end of the line, if they stop working, you need to check the command line editor option in bash. There are two command line editors for bash: emacs or vi. The default editor is emacs, that is why ctrl+A and ctrl+E works by default. Don't regard ctrl+A ctrl+E as built-in feature of bash, it can be disabled by changing editor to vi.


set -o #list current value of the options
emacs off
vi on
set -o vi #enable vi as editor, it will disable emacs automatically like set +o emacs does
set -o emacs #enable emacs as editor, it will disable vi automatically like set +o vi does


Command Editing -- Cursor Movement in command mode for vi
l (el) Move the cursor forward one character
h Move the cursor back one character
w Move the cursor forward one word
b Move the cursor back one word
fc Find character c in the line
0 (zero) Cursor to the start of the line
$ Cursor to the end of the line
l, h, w, f and b can be preceded by a number, thus 2b moves the cursor back two words, and 3fx finds the third occurrence of x in the line. In emacs and gmacs mode, cursor movement is different.

Command Editing -- Cursor Movement in emacs/gmacs
CONTROL-F Move the cursor forward one character
CONTROL-B Move the cursor back one character
ESCAPE then f Move the cursor forward one word
ESCAPE then b Move the cursor back one word
CONTROL-A Cursor to the start of the line
CONTROL-E Cursor to the end of the line


http://www.gnu.org/software/bash/manual/bashref.html#Command-Line-Editing

Lastly, set -o options work for ksh as well, but csh/sh doesn't support it.