“It lies in the power of every man, either permissively to hasten, or actively to shorten, but not to lengthen or extend the limits of his natural life. He only (if any) hath the art to lengthen his taper, that put it to best advantage.”
Francis Quarles
Here are some nifty command line scripts which come in handy:
- Show the lines in a file which are uncommented and not empty
grep -E -v “#|^$” file
or alternatively (just to use sed)
grep -E -v “#” | sed ‘/^$/d’ - Create 10 txt files
touch test{0..9}.txt - Move all txt files to bak files
for i in *txt
do
j=`echo $i | sed ‘s/txt/bak/’`
mv $i $j
done - Find out who is using the most disk space
du -hs /home/* | sort -n - Selecting the most recent file in a directory
ls -rt | tail -1 - Excluding the grep command from ps aux
Lets say you want to grep the process list for all vi processes. The resulting list will contain the grep command itself. To avoid this use
ps aux | grep [v]i - Compare the differences between a remote & local file
ssh user@server cat remote.txt | diff -y local.txt – - Quickly create a dated backup
Firstly create an alias in your .bashrc
echo “alias d=’date +%F” >> .bashrc
Restart your terminal & try
mv file.txt{,.$(d)} - Quickly remove all whitespace
cat file.txt | sed ‘s/\s\+//g’ - Columnize output
column -s : -t /etc/passwd
would format passwd in columns using : as a delimiter. - Get the total weight of certain files in a directory
du -hc *txt
or
ls -al *txt | awk ‘{ print; total += } END { print total / 1.024e+9 }’ - Count any number of lines before or after a search match
egrep -A 15 test testytest.txt
Provides the next 15 lines after the match.
egrep -B 15 test testytest.txt
Provides the 15 lines before the match. - List services running on a machine
netstat -nptl | egrep ‘^tcp’ | awk ‘{if($7!=”-“){print $7}}’ | cut -d/ \ -f2 | sort -u - How much RAM does a machine have?
egrep ‘MemTotal’ /proc/meminfo | awk ‘{print $2/1024, “MB”}’ - How many disks does a machine have?
fdisk -l 2>/dev/null | egrep ‘/dev/(s|xv)d[a-z]:’ | \
awk ‘{count++}END{print count}’