Daily Archives: 7 November 2014

How to: remove prefix and suffix from a variable in bash 1

string=${string#$prefix}; #Remove prefix
string=${string%$suffix}; #Remove suffix
echo $string; #Prints "hello_kitty"

In the above example we have as input the variable string that contains following /scripts/log/mount_hello_kitty.log.

We want to remove from that variable the prefix, which is /scripts/log/mount_ and the suffix, which is .log.

The above code will replace in place the input that is contained in the variable string and remove the prefix and suffix we defined in the respective variables.

string=${string#$prefix} returns a copy of string after the prefix was removed from the beginning of the variable.

string=${string%$suffix} returns a copy of string after the suffix was removed from the end of the variable.

How to: Extract all usernames that are logged in from who

who | cut -d ' ' -f 1 | sort -u

who: will show who is logged on

cut  -d ‘ ‘ -f 1: will remove all sections from each line except for column 1. It will use the space character as the delimiter for the columns

sort -u: it will sort the usernames and remove duplicate lines. So if a user is logged in multiple times you will get that username only once.
In case you want to filter out root user from this list you can do it as follows:

who | cut -d ' ' -f 1 | sort -u | grep -v 'root'