Python for Network Engineers

Bash scripting 101

By George El. • January 2019 • Reading time: 6 minutes

In this post I describe basic features of the bash shell Variables Variables by convention use uppercase characters and are case sensitive. There are builtin variables like HOME, USER, PWD and user defined variables. To print a variable you precede it with $ or put it in ${} $ VAR1=1 $ echo "$VAR1" 1 $ VAR2="Hello" $ echo "$VAR2" Hello $ echo $USER geo555 $>echo ${USER} geo555 you may have noticed that I enclose variables in quotes when printing them.

How to Sort IP Addresses in Bash in One Line

By George El. • January 2019 • Reading time: 1 minute

Lets assume we have the following file with IPs and we want to sort them. Obviosuly if we sort them like strings, we won’t get what we want. We want to sort on the first octet, then the second, then the third, then the fourth. more IPs.txt 255.1.1.1 1.1.1.1 120.10.1.5 120.

Rename Files From 1.Name or Name1 to 01Name

By George El. • January 2019 • Reading time: 3 minutes

there is nothing more annoying than seeing unordered files, and this happens a lot when you have numbers in front of files like 1.file, 2.file etc. the command is ls -1 | sed -r -e 's/([a-zA-z]+)([0-9]+)(\.txt)/\0 \2 \1 \3/' | xargs -n4 printf "%s %02d%s%s\n" | xargs -n2 mv and we will break it down

Find the Total Size of All Files With Certain Extension with one Line

By George El. • January 2019 • Reading time: 2 minutes

find all files with a certain extension in current directory and add the file sizes to calculate total file size in Mbytes find . -iname "*.txt" | xargs ls -l | awk '{print $5 }' | paste -sd+ | bc | awk '{print $1/1024/1024 }' the above example finds all files ending in txt, starting from the current directory.

Bash expansion

By George El. • January 2019 • Reading time: 4 minutes

In this post I am going to talk about expansion in bash. But first we need to talk about how bash interprets each line in a script. Bash does five things. Words that are not variable assignments or redirections are expanded First word becomes command remaining words become arguments Redirections are performed Variables are expanded and assigned does not include brace and process substitution assignments are valid only for this command if there is no command assignemnt becomes permanent Alias expansion is applied if the command was not quoted The identified function, builtin or external program is executed with the arguments There are several types of expansion and are done in the following order and from left to right: