*NIX commands - Tips and handy one-liners

There will be situations wherein we will have to do mundane work like adjusting text in a specific pattern or filtering data and rely heavily on Notepad++ or TextPad wondering a direct command would be an absolute life-saver.  Hopefully these tips and one-liners should come in handy during your work.

Description: To print the home directory of a user 
Command grep -i <username> /etc/passwd | awk -F":" '{print $6}'

Description: To print only file names from the output of long listing ls command
Command ls -ltr | awk '{print $9}'

Tip: Use "grep -vi grep" while searching for a process using grep with "ps -ef" command to avoid confusion
Command ps -ef  | grep -vi grep | grep -i <process_name>

Tip: Use "sort" before using "uniq" while trying to eliminate duplicates
Command : <standard output> | sort | uniq

Description: To find and replace in the standard output or in a file. Though sed helps in this case it will not work well in some UNIX based Operating Systems
Command echo "Hello thEre" | perl -pi -e "s/there/World/gi"
Command perl -pi -e "s/<existing_word>/<new_word>/gi" <filename>
gi will help in performing a case insensitive global replace

Tip: Use "cat -n" to print line number in standard output
Command : <standard output> | cat -n
Command : cat -n <filename>

Tip: Special characters like ^M causing trouble and not visible in normal editor, use "cat -evt"
Command cat -evt <filename>


Description: To see the commands being executed by a Shell Script
AIX Command proctree <PID>
Linux Command pstree <PID>

Description: To perform addition of all values in a column using awk 
Command ls -ltr |awk '{sum += $2} END {print sum}'
Here from the output of ls command, we are adding all the values in column 2

Description: To print single quote with awk 
Commandawk '{print "\047" $0 "\047"}' filename
Commandawk -v q="'" '{print q $0 q}' filename

Description: How to change the putty terminal name
Commandprintf "\033]0;desired_name\007"
Commandecho "\033]0;desired_name\007"

Description: How to prefix a specific line number with specific character. Example prefix line number 32 in a file with --
Commandsed -i '32s/^/--/' <filename>



No comments:

Post a Comment