Learn how to create custom string functions in Bash with our comprehensive guide. Explore common functions like ltrim, rtrim, trim, reverse, len, uppercase, lowercase, substitute, capitalize, rot13, index, join, substring, repeat, and lastindex. Improve your Bash scripting skills by mastering these essential string functions and unlocking new possibilities for your projects.

Advanced String Operations in Bash: Building Custom Functions

  • Last Modified: 17 Aug, 2023

In this blog post, we dive into the world of Bash scripting and explore how to create custom string functions to perform advanced string operations. We cover essential functions like ltrim, rtrim, trim, reverse, and len, and provide code examples to help you build these functions in your Bash scripts. By the end of this article, you’ll have a better understanding of how to create custom functions to save time and streamline your Bash scripting workflow.


Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


Hey there, let me tell you a story about Bash and strings!

So, Bash is like a master chef that can cook up all sorts of delicious scripts and programs. And just like any chef, sometimes Bash needs to work with strings - you know, those little pieces of text that can make or break your code.

Now, Bash is pretty good at working with strings out of the box. But sometimes, you need to do some fancier stuff - like trimming whitespace, reversing the order of characters, or finding the length of a string. And that’s where custom string functions come in!

Custom string functions are like little sous chefs that work alongside Bash to help with all those string operations that you need. They’re super easy to create, and can be a lifesaver when you’re trying to make your code more efficient and powerful.

In this blog post, we’re gonna show you how to create some common custom string functions in Bash, like ltrim, rtrim, trim, reverse, and len. With these functions in your arsenal, you’ll be able to slice and dice strings like a pro in no time!

So, grab your chef’s hat and get ready to cook up some awesome Bash scripts with custom string functions!

LTRIM

Alright, let’s have some fun with this one!

Listen up, because I’m about to introduce you to the coolest thing since sliced bread: the ltrim function in Bash!

So, you know how sometimes you have a string with some pesky leading whitespace characters that just won’t go away? Well, that’s where ltrim comes in. This function is like a magic eraser that zaps all those unwanted spaces away from the beginning of your string.

Now, I know what you’re thinking - “But how does it work?!” Well, my friend, it’s all thanks to the power of Bash parameter expansion. This feature lets you do all sorts of cool stuff with strings, like removing characters from the beginning or end of a string.

Here’s the code for the ltrim function:

function ltrim {
    echo "${1#"${1%%[![:space:]]*}"}"
}

I know it looks a little intimidating, but don’t worry - it’s actually super simple. All this function does is take your input string, and then uses parameter expansion to remove any leading whitespace characters.

So there you have it, folks - the ltrim function is your new best friend when it comes to cleaning up those messy strings in Bash. Give it a try and see how much easier your string operations become!

RTRIM

Oh boy, do I have a treat for you - it’s the rtrim function in Bash!

This little gem is just like the ltrim function we talked about earlier, but with a twist: instead of removing leading whitespace characters from a string, it removes trailing whitespace characters from the end of the string.

Now, I know what you’re thinking - “But why do I need rtrim when I have ltrim?!” Well, my friend, sometimes you need to trim from the other end of the string, like when you’re dealing with file paths or URLs. That’s where rtrim comes in handy.

Here’s the code for the rtrim function:

function rtrim {
    echo "${1%"${1##*[![:space:]]}"}"
}

Again, I know it might look a little crazy, but it’s actually pretty simple. This function takes your input string and uses parameter expansion to remove any trailing whitespace characters from the end of the string.

So there you have it - the rtrim function in all its glory. Now you can clean up those pesky whitespace characters from the beginning and end of your strings with ease. Go forth and trim!

TRIM

Hey hey, get ready to meet the superstar of string functions - it’s the trim function in Bash!

This function is like the love child of the ltrim and rtrim functions we talked about earlier. It takes your input string and removes both leading and trailing whitespace characters, leaving you with a clean and tidy string that’s ready to use.

Here’s the code for the trim function:

function trim {
    echo "$(rtrim "$(ltrim "$1")")"
}

Okay, okay, I know it looks a little intimidating with all those quotes and curly braces, but don’t worry - it’s not as complicated as it seems.

This function takes your input string and uses parameter expansion to remove any leading whitespace characters from the beginning of the string, and any trailing whitespace characters from the end of the string. The result is a trimmed string that’s clean and ready to use.

So there you have it - the trim function is like the superhero of string functions, swooping in to save the day and leave your strings looking their best. Use it wisely, my friend!

REVERSE

Hold onto your hats, folks, because we’re about to talk about the reverse function in Bash!

This little function is like a magician, taking your input string and flipping it around so that the characters are in reverse order. It’s like seeing your reflection in a mirror - but for strings!

So, how does it work? Well, the reverse function uses a loop to iterate over each character in your input string, building a new string in reverse order as it goes. This loop is like a little assembly line, churning out a brand new string that’s the reverse of the original.

Here’s the code for the reverse function:

function reverse {
  local str="$1"
  local reversed=""
  local len=${#str}
  for ((i=$len-1; i>=0; i--))
  do
    reversed="$reversed${str:$i:1}"
  done
  echo "$reversed"
}

I know it looks a little scary with all those variables and loops, but trust me - it’s actually pretty straightforward. This function takes your input string, gets the length of the string, and then uses a loop to iterate over each character in the string. For each character, it adds that character to the beginning of a new string called reversed.

Once the loop has finished iterating over all the characters in the string, the reverse function outputs the reversed string, which is now a mirror image of the original input string.

So there you have it - the reverse function is like a time machine for strings, taking you back in time and showing you the characters in reverse order. Use it wisely, my friend!

LEN

This little function is like a measuring tape for your strings - it helps you figure out just how long they are. With len, you can easily find out how many characters are in your string, which can be super useful for all sorts of string operations.

So, how does it work? Well, the len function uses a Bash built-in feature that returns the length of a variable. This feature is like a magic wand, waving over your string and telling you exactly how many characters are in there.

Here’s the code for the len function:

function len {
    echo "${#1}"
}

I know it looks super simple (and it is!), but that’s the beauty of it. This function takes your input string, and then uses the ${#str} syntax to return the length of the string.

So there you have it - the len function is like a quick and easy way to find out the length of your strings in Bash. Use it whenever you need to know just how long your strings are!

UPPERCASE

This function is like a magic wand that takes your input string and transforms it into all uppercase characters. It’s like a big, bold statement that says “Hey, look at me, I’m in ALL CAPS!”

So, how does it work? Well, the uppercase function uses a Bash built-in command called “tr”. This command is like a translator, taking your input string and replacing all lowercase characters with their uppercase equivalents.

Here’s the code for the uppercase function:

function uppercase {
    echo "$1" | tr '[:lower:]' '[:upper:]'
}

I know it might look a little intimidating with all those quotes and colons, but don’t worry - it’s actually pretty simple. This function takes your input string, and then uses the “tr” command to replace all lowercase characters with their uppercase equivalents.

So there you have it - the uppercase function is like a superhero that transforms your strings into ALL CAPS. Use it wisely, my friend!

LOWERCASE

This little function is like a chameleon that takes your input string and transforms it into all lowercase characters. It’s like a cool and collected statement that says “Hey, look at me, I’m in all lowercase!”

So, how does it work? Well, just like the uppercase function, the lowercase function also uses the Bash built-in command called “tr”. This command is like a wizard that takes your input string and replaces all uppercase characters with their lowercase equivalents.

Here’s the code for the lowercase function:

function lowercase {
    echo "$1" | tr '[:upper:]' '[:lower:]'
}

I know it might look a little confusing with all those quotes and colons, but trust me - it’s actually pretty simple. This function takes your input string, and then uses the “tr” command to replace all uppercase characters with their lowercase equivalents.

So there you have it - the lowercase function is like a ninja that can stealthily transform your strings into all lowercase. Use it wisely, my friend!

SUBSTITUTE

Hold onto your hats, folks, because we’re about to talk about the substitute function in Bash!

This function is like a shape-shifter that takes your input string and replaces all occurrences of a search string with a replacement string. It’s like having a magic wand that can transform your strings into whatever you want them to be!

So, how does it work? Well, the substitute function uses a Bash built-in command called “sed”. This command is like a surgeon that can perform intricate replacements on your input string, based on a search string and a replacement string that you provide.

Here’s the code for the substitute function:

function substitute {
    echo "$1" | sed "s/$2/$3/g"
}

I know it looks a little intimidating with all those quotes and slashes, but don’t worry - it’s actually pretty simple. This function takes your input string, as well as the search string and replacement string that you want to use, and then uses the “sed” command to perform the substitution.

TRUNCATE

The truncate function truncates a string to a specified length and appends an ellipsis ("…") at the end. Here’s the code for the truncate function:

function truncate {
    local str="$1"
    local len="$2"
    if [ "${#str}" -gt "$len" ]; then
        echo "${str:0:$len}..."
    else
        echo "$str"
    fi
}

COUNT

This little function is like a detective that can count the number of occurrences of a search string in your input string. It’s like having a magnifying glass that can zoom in on all the instances of your search string!

So, how does it work? Well, the count function uses a Bash built-in feature that counts the number of times a pattern appears in a string. This feature is like a calculator that can add up all the instances of your search string in your input string.

Here’s the code for the count function:

function count {
    echo "$1" | awk -v FS="$2" '{print NF-1}'
}

I know it might look a little complicated with all those quotes and colons, but trust me - it’s actually pretty simple. This function takes your input string, as well as the search string that you want to count, and then uses the “awk” command to perform the counting.

The awk command works by splitting the input string into fields, using the search string as the field separator. It then prints the number of fields minus one, which gives you the number of occurrences of the search string in the input string.

So there you have it - the count function is like a detective that can count all the instances of your search string in your input string. Use it whenever you need to know how many times a specific string appears in your input string!

SPLIT

This little function is like a knife that can cut your input string into pieces, based on a specified delimiter. It’s like having a chef’s knife that can chop up your string into bite-sized chunks!

So, how does it work? Well, the split function uses a Bash built-in command called “read”. This command is like a waiter that serves up your input string in small, manageable pieces, based on a specified delimiter.

Here’s the code for the split function:

function split {
    local IFS="$2"
    read -ra arr <<< "$1"
    echo "${arr[@]}"
}

I know it might look a little confusing with all those variables and commands, but trust me - it’s actually pretty simple. This function takes your input string, as well as the delimiter that you want to use to split the string, and then uses the “read” command to perform the splitting.

The read command works by setting the Internal Field Separator (IFS) to the specified delimiter, and then reading the input string into an array called arr. Each element of the array corresponds to a substring between the delimiters.

Finally, the split function outputs the array using the "${arr[@]}" syntax, which outputs all the elements of the array separated by spaces.

So there you have it - the split function is like a chef’s knife that can chop up your input string into small, manageable pieces. Use it whenever you need to split your string based on a specified delimiter!

CAPITALIZE

This function is like a stylist that can give your input string a brand new look by capitalizing the first letter of each word. It’s like putting on a fancy hat or a snazzy pair of shoes - it just makes your string look more polished and put together!

So, how does it work? Well, the capitalize function uses a Bash built-in command called “sed”. This command is like a fashion designer that can make subtle changes to your input string, based on a pattern that you provide.

Here’s the code for the capitalize function:

function capitalize {
    echo "$1" | sed 's/\b\([a-z]\)/\u\1/g'
}

I know it might look a little intimidating with all those slashes and letters, but don’t worry - it’s actually pretty simple. This function takes your input string, and then uses the “sed” command to perform the capitalization.

The sed command works by searching for each word boundary in the input string, and then capitalizing the first letter of each word using the \u syntax. The . in the regular expression matches any character, while the \b matches a word boundary.

So there you have it - the capitalize function is like a stylist that can give your input string a whole new look by capitalizing the first letter of each word. Use it whenever you need to make your string look more polished and professional!

ROT13

This function is like a secret agent that can encode your input string using the ROT13 cipher. It’s like sending your string through a secret decoder ring that only you and your friends know how to use!

So, how does it work? Well, the rot13 function uses a Bash built-in command called “tr”. This command is like a translator that can take your input string and replace each letter with the letter 13 places down the alphabet.

Here’s the code for the rot13 function:

function rot13 {
    echo "$1" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
}

I know it might look a little confusing with all those letters and numbers, but trust me - it’s actually pretty simple. This function takes your input string, and then uses the “tr” command to perform the ROT13 encoding.

The tr command works by replacing each character in the input string with the character 13 places down the alphabet. The ‘A-Za-z’ range specifies that it should only be applied to uppercase and lowercase letters, while the ‘N-ZA-Mn-za-m’ range specifies the mapping for each letter.

So there you have it - the rot13 function is like a secret agent that can encode your input string using the ROT13 cipher. Use it whenever you need to send a secret message to your friends!

INDEX

This little function is like a detective that can find the position of the first occurrence of a search string in your input string. It’s like having a magnifying glass that can zoom in on the specific location of your search string!

So, how does it work? Well, the index function uses a Bash built-in command called “expr”. This command is like a calculator that can perform simple arithmetic operations, and also has the ability to search for a pattern in a string.

Here’s the code for the index function:

function index {
    local str="$1"
    local search="$2"
    expr index "$str" "$search"
}

I know it looks pretty simple, but that’s because it is! This function takes your input string, as well as the search string that you want to look for, and then uses the “expr” command to find the position of the first occurrence of the search string in the input string.

The expr command works by searching for the first occurrence of the search string in the input string, and then returning the position of the first character of the search string.

So there you have it - the index function is like a detective that can quickly find the position of the first occurrence of your search string in your input string. Use it whenever you need to know the specific location of a specific string!

JOIN

This little function is like a glue that can join an array of strings into a single string, separated by a specified delimiter. It’s like sticking all your strings together into one big happy family!

So, how does it work? Well, the join function uses a Bash built-in command called “printf”. This command is like a formatting tool that can take your input strings and format them into a single string, separated by a specified delimiter.

Here’s the code for the join function:

function join {
    local IFS="$1"
    shift
    printf '%s' "$*"
}

I know it might look a little intimidating with all those quotes and symbols, but don’t worry - it’s actually pretty simple. This function takes your delimiter, as well as an array of strings that you want to join together, and then uses the “printf” command to perform the joining.

SUBSTRING

This function is like a tailor that can cut a piece of your input string into a substring, starting at a specified index and of a specified length. It’s like trimming a piece of fabric to fit just right!

So, how does it work? Well, the substring function uses two Bash built-in commands: “expr” and “cut”. The “expr” command is like a calculator that can perform simple arithmetic operations, while the “cut” command is like a pair of scissors that can cut your input string into pieces.

Here’s the code for the substring function:

function substring {
    local str="$1"
    local start="$2"
    local len="$3"
    echo "${str:$start:$len}"
}

I know it might look a little confusing with all those variables and commands, but trust me - it’s actually pretty simple. This function takes your input string, as well as the starting index and length of the substring that you want to extract, and then uses the “expr” command to calculate the end index of the substring.

Finally, the substring function uses the “cut” command to extract the specified substring from the input string, starting at the specified starting index and ending at the calculated end index.

So there you have it - the substring function is like a tailor that can cut a piece of your input string into a substring, starting at a specified index and of a specified length. Use it whenever you need to extract a specific part of your string!

REPEAT

This little function is like a copy machine that can create a copy of your input string, repeated a specified number of times. It’s like printing out multiple copies of the same document!

So, how does it work? Well, the repeat function uses a Bash loop to repeat your input string a specified number of times.

Here’s the code for the repeat function:

function repeat {
    local str="$1"
    local count="$2"
    for ((i=1; i<=$count; i++))
    do
        echo -n "$str"
    done
    echo
}

I know it might look a little scary with all those parentheses and variables, but don’t worry - it’s actually pretty simple. This function takes your input string, as well as the number of times that you want to repeat the string, and then uses a Bash loop to perform the repeating.

The for loop starts at 0 and goes up to the specified number of repetitions, incrementing by 1 each time. Inside the loop, the echo -n command outputs your input string without a newline character, so that each repetition is on the same line.

So there you have it - the repeat function is like a copy machine that can create multiple copies of your input string. Use it whenever you need to repeat a string a specified number of times!

LASTINDEX

This function is like a reverse detective that can find the position of the last occurrence of a search string in your input string. It’s like looking for a needle in a haystack - but starting from the end!

So, how does it work? Well, the lastindex function uses two Bash built-in commands: “expr” and “rev”. The “expr” command is like a calculator that can perform simple arithmetic operations, while the “rev” command is like a mirror that can flip your input string around.

Here’s the code for the lastindex function:

function lastindex {
    local str="$1"
    local search="$2"
    local reversed=$(echo "$str" | rev)
    local pos=$(expr index "$reversed" "$search")
    local len=${#search}
    local strlen=${#str}
    echo $((strlen - pos - len + 2))
}

I know it might look a little complicated, but don’t worry - it’s actually pretty straightforward. This function takes your input string, as well as the search string that you want to look for, and then uses the “rev” command to reverse the input string.

After that, the lastindex function uses the “expr” command to find the position of the last occurrence of the search string in the reversed input string. It then calculates the position of the last occurrence in the original string by subtracting the index from the length of the string and adding 1.

Finally, the lastindex function outputs the position of the last occurrence of the search string in the original input string.

So there you have it - the lastindex function is like a reverse detective that can quickly find the position of the last occurrence of your search string in your input string. Use it whenever you need to search from the end of your string!

SHUFFLE

This function takes a string as input, and then shuffles the characters in that string so that they’re in a completely random order. The resulting shuffled string is then returned as output.

This function can be super useful if you need to generate randomized strings for things like security purposes or for generating passwords. With shuffle, you can create completely unique strings that are much harder for someone to guess or crack.

So, the next time you need to generate a random string for something, give shuffle a try! It’s a fun and powerful Bash function that can help make your code more secure and more versatile.

Here’s the code for the shuffle function:

shuffle() {
  local str="$1"
  local len=${#str}
  local shuffled=""
  local chars=($(echo "$str" | fold -w1))
  while [ ${#chars[@]} -gt 0 ]; do
    local rand=$((RANDOM % ${#chars[@]}))
    shuffled+="${chars[$rand]}"
    chars=("${chars[@]:0:$rand}" "${chars[@]:$((rand+1))}")
  done
  echo "$shuffled"
}

Here’s how the function works:

  • The function first stores the input string in a local variable called str, and gets the length of the string using ${#str}.

  • The function creates an empty variable called shuffled that will be used to store the shuffled string.

  • The function uses the fold -w1 command to split the input string into an array of individual characters. This array is stored in a variable called chars.

  • The function enters a while loop that continues as long as the chars array has more than 0 elements. Inside the loop, the function generates a random index between 0 and the length of the chars array, and uses that index to select a random character from the array. This character is added to the shuffled variable using the += operator.

  • The function removes the selected character from the chars array using the “${chars[@]:0:$rand}” “${chars[@]:$((rand+1))}” syntax, which slices the array into two parts: one that contains all elements up to the selected index, and one that contains all elements after the selected index. This updated array is then stored back into the chars variable.

  • Once the while loop has finished, the function outputs the shuffled variable, which contains the shuffled version of the input string.

This shuffle function uses a number of complex Bash features, such as array slicing and the fold command, to create a randomized version of a string. While this function may not be directly applicable to all use cases, it demonstrates the power and flexibility of Bash when it comes to manipulating strings.

RANDOM_STRING

Yo, listen up! I’m about to tell you about a totally random and wacky Bash function called random_string!

So, this function is like a mad scientist who takes an integer as input - which tells them how many characters the random string should have - and then starts cooking up a crazy concoction using the openssl command! They stir in a bunch of random bytes and mix it all up until they have a string that’s completely random and unpredictable!

And when the scientist is done with their crazy experiment, they hand you the resulting random string on a platter (well, not really a platter, more like the Bash terminal screen). You can use this string for anything you want - maybe it’s a top-secret password, maybe it’s a random ID for your latest project, or maybe it’s just a fun way to mess with your friends!

So there you have it - the random_string function is a fun and totally unpredictable way to generate random strings in your Bash scripts. Give it a try and see what kind of crazy randomness you can come up with!

random_string() {
  local len="$1"
  local random_bytes="$(openssl rand -base64 $((len * 2)) | tr -d '\n')"
  echo "${random_bytes:0:len}"
}

And here’s how it works:

  • The function first stores the input integer in a local variable called len.

  • The function generates random bytes using the openssl rand -base64 command. This command generates a string of random characters that is twice as long as the desired length of the output string (since each base64 character represents 6 bits of data).

  • The resulting random string is stored in a variable called random_bytes.

  • The function uses the tr -d '\n' command to remove any newline characters from the random_bytes variable.

  • Finally, the function uses ${random_bytes:0:len} to extract the first len characters from the random_bytes variable, and then outputs this shortened random string.

With the random_string function, you can easily generate random strings of any desired length. This can be useful for generating unique IDs, session tokens, or any other situation where you need to generate a random string.

SANITIZE

Are you tired of dealing with input strings that are as dirty as a mud puddle? Well, have no fear, because our new Bash string function is here to sanitize your input like a germaphobe!

Introducing the sanitize function - the cleanest function in all the land. This function removes all non-alphanumeric characters from a string, except for those specified in an allowed list. It’s like a superhero, fighting off all the bad characters to leave your input string sparkling clean!

And the best part? You get to choose which characters are allowed to stay, so you can customize the cleanliness to your liking. It’s like being the boss of your own cleaning crew!

Here’s the code for the sanitize function:

sanitize() {
  local str="$1"
  local allowed="$2"
  local sanitized=$(echo "$str" | sed "s/[^[:alnum:]$allowed]//g")
  echo "$sanitized"
}

Now, you may be wondering how to use this super-sanitizing function. Well, it’s easy peasy lemon squeezy! Just pass in the input string you want to sanitize and a list of allowed characters. The function will take care of the rest, leaving your input string as clean as a whistle.

Here’s an example of how to use the sanitize function:

# Remove all non-alphanumeric characters except for spaces
input="Hello, world! This is some input."
allowed=" "
output=$(sanitize "$input" "$allowed")
echo "$output"  # Output: "Hello world This is some input"

In the example above, we’re removing all non-alphanumeric characters from the input string, except for spaces. It’s like we’re leaving the spaces alone, so they can breathe and enjoy the fresh, clean air.

So there you have it - the sanitize function is like a germaphobe’s dream come true. It’s like having your own cleaning crew, but for strings!

PARSE_CSV

Do you ever feel like you’re drowning in a sea of CSV files, desperately trying to make sense of all that data? Fear not, because our new Bash string function is here to rescue you like a lifeguard!

Introducing the parse_csv function - the hero we all need when it comes to handling those pesky spreadsheets. This function takes a CSV file and turns it into an array of arrays, so you can easily navigate through the data like a boss.

And the best part? You get to customize the delimiter, so you can chop through the data with the precision of a ninja! It’s like having your own team of data analysts at your fingertips, but without all the fancy suits and high salaries.

Here’s the code for the parse_csv function:

parse_csv() {
  local file="$1"
  local delimiter="${2:-,}"
  local rows=()
  while IFS="$delimiter" read -ra fields; do
    rows+=("${fields[@]}")
  done < "$file"
  echo "${rows[@]}"
}

Here’s how you can use the parse_csv function:

# Parse a CSV file into an array of arrays
file="data.csv"
delimiter=","
data=$(parse_csv "$file" "$delimiter")
echo "${data[0][0]}"  # Output: "John Smith"
echo "${data[0][1]}"  # Output: "42"
echo "${data[1][0]}"  # Output: "Jane Doe"
echo "${data[1][1]}"  # Output: "27"

In the example above, we’re parsing a CSV file into an array of arrays. The function reads in each line of the file and splits it into an array of fields using the specified delimiter (or a comma by default). The resulting array of fields is then appended to the rows array.

Feel free to modify this function to fit your specific use case. You can customize the delimiter and how the data is outputted. Let me know if you have any questions or if there’s anything else I can help you with!

CHECK_PASSWORD_STRENGTH

This function takes a password string as input and checks its strength, based on a set of criteria such as length, complexity, and uniqueness. This can be useful for ensuring that users choose strong passwords that are difficult to crack.

Now, imagine you’re an IT administrator at a company, and you’re in charge of setting password policies for all the employees. You want to make sure that everyone chooses strong passwords that are difficult to crack, but you don’t want to make the password requirements too complex or difficult to remember. That’s where the check_password_strength function comes in - it allows you to easily check the strength of a password and provide feedback to the user on how to improve it.

But beware - if your password is weak, you might as well be rolling out the red carpet for hackers to come and steal all your sensitive data. With the check_password_strength function, you can ensure that your passwords are like a fortress of security, and that your data is safe and sound.

Here’s the code for the check_password_strength function:

check_password_strength() {
  local password="$1"
  local length=${#password}
  local upper=$(echo "$password" | grep -o "[A-Z]" | sort -u | wc -l)
  local lower=$(echo "$password" | grep -o "[a-z]" | sort -u | wc -l)
  local digits=$(echo "$password" | grep -o "[0-9]" | sort -u | wc -l)
  local special=$(echo "$password" | grep -o "[^a-zA-Z0-9]" | sort -u | wc -l)
  local score=$((length + upper + lower + digits + special))
  if ((score < 10)); then
    echo "Weak password detected! Try adding more complexity."
  elif ((score < 20)); then
    echo "Moderate password detected. Not bad, but could be better."
  else
    echo "Strong password detected! You're like a fortress of security!"
  fi
}

Here’s how you can use the check_password_strength function:

# Check the strength of a password
password="MySuperSecurePassword123!"
check_password_strength "$password"
# Output: "Strong password detected! You're like a fortress of security!"

In the example above, we’re checking the strength of a password using the check_password_strength function. The function calculates a score for the password based on its length, complexity, and uniqueness. If the score is less than 10, it’s considered weak. If it’s between 10 and 20, it’s considered moderate. And if it’s greater than 20, it’s considered strong.

So go ahead and use the check_password_strength function - your boss and your customers will thank you for it!

GENERATE_SLUG

This function takes a string as input and generates a URL-friendly slug by removing special characters, replacing spaces with hyphens, and converting all characters to lowercase. This can be useful for generating clean URLs for blog posts, product pages, and other web content.

Here’s the code for the generate_slug function:

generate_slug() {
  local string="$1"
  local slug=$(echo "$string" | tr -cd '[:alnum:][:space:]' | tr '[:space:]' '-' | tr '[:upper:]' '[:lower:]' | sed 's/-$//')
  echo "$slug"
}

Here’s how you can use the generate_slug function:

# Generate a URL-friendly slug from a string
string="Hello, World! This is a Test."
slug=$(generate_slug "$string")
echo "$slug"  # Output: "hello-world-this-is-a-test"

In the example above, we’re generating a URL-friendly slug from a string by removing special characters, replacing spaces with hyphens, and converting all characters to lowercase.

Now, let’s say you’re a blogger, and you want to create a new blog post titled “The Ultimate Guide to Bash Scripting”. You want the URL for the post to be clean and SEO-friendly, so you decide to use the generate_slug function to create a slug for the post.

You type in the title of the post and hit enter: “The Ultimate Guide to Bash Scripting”. The function immediately gets to work, removing all the special characters and replacing spaces with hyphens, until you’re left with a clean and shiny slug: “the-ultimate-guide-to-bash-scripting”.

It’s like having your own personal string cleaner, scrubbing away all the dirt and grime until you’re left with a pristine and sparkling URL. It’s like a toothbrush for your strings - cleaning them up and making them shine like a diamond.

So go ahead, give the generate_slug function a try. Your URLs will thank you for it!

REPLACE

This function replaces all occurrences of a specified substring with another substring.

replace () {
    local original="$1"
    local replacement="$2" 
    local input="$3" 
    echo "${input//$original/$replacement}" 
}

#Usage
result=$(replace "apple" "banana" "I like apple and apple pie.") 
echo "$result"
#Output: "I like banana and banana pie."

COUNT_WORDS

This function counts the number of words in a given string.

count_words(){
    local input="$1"
    local word_count=$(echo "$input" | wc -w)
    echo "$word_count"
}
 
count=$(count_words "Hello, how are you?") 
echo "Word count: $count"
# Output: "Word count: 4"

REMOVE_SPECIAL_CHARS

This function removes all special characters from a string.

remove_special_chars (){
    local input="$1"
    sanitized=$(echo "$input" | tr -d '[:punct:]')
    echo "$sanitized"
}

#Usage
  clean_string=$(remove_special_chars "Hello, @world!") 
  echo "$clean_string"
  #Output: "Hello world"

REVERSE_WORDS

This function reverses the order of words in a string.

reverse_words(){
    local input="$1" 
    reversed=$(echo "$input" | awk '{ for (i=NF; i>0; i--) printf("%s ",$i); print "" }') 
    echo "$reversed" 
}

#Usage
  reversed_sentence=$(reverse_words "This is a sentence.") 
  echo "$reversed_sentence"
  #Output: "sentence. a is This"

STRIP_HTML_TAGS

This function removes HTML tags from a given string.

strip_html_tags(){
    local input="$1"
    cleaned=$(echo "$input" | sed -e 's/<[^>]*>//g')
    echo "$cleaned"
}

#Usage
  text_without_tags=$(strip_html_tags "<p>This is <b>bold</b> text.</p>") 
  echo "$text_without_tags"
#Output: "This is bold text."

CAMEL_TO_SNAKE_CASE

This function converts a string from CamelCase to snake_case.

camel_to_snake_case() {
    local input="$1"
    snake_case=$(echo "$input" | sed -E 's/([a-z0-9])([A-Z])/\1_\L\2/g' | tr '[:upper:]' '[:lower:]')
    echo "$snake_case"
}
# Usage
snake_case_str=$(camel_to_snake_case "camelCaseString")
echo "$snake_case_str"  # Output: "camel_case_string"

COUNT_OCCURRENCES

This function counts the occurrences of a substring within a larger string.

count_occurrences() {
    local substring="$1"
    local input="$2"
    echo "$input" | grep -o "$substring" | wc -l
}
# Usage
count=$(count_occurrences "apple" "I like apple and apple pie.")
echo "Occurrences: $count"  # Output: "Occurrences: 2"

TRANSFORM_TEXT

The function will take an input string, and through a series of operations, it will remove special characters, convert the string to title case, and replace specific words with synonyms. This demonstrates a more intricate and practical example of string manipulation. We’ll use sed, awk, and an API to achieve this.

Before using this function, make sure you have curl installed for making HTTP requests.

transform_text() {
    local input="$1"

    # Remove special characters
    cleaned=$(echo "$input" | tr -d '[:punct:]')

    # Convert to title case
    title_case=$(echo "$cleaned" | awk '{ for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2)); }1')

    # Initialize an empty string for the transformed result
    transformed_result=""

    # Iterate over each word in the title-cased text
    for word in $title_case; do
        # Fetch the synonym for the word
        synonym=$(curl -s "https://api.datamuse.com/words?ml=$word" | jq -r '.[0].word')

        # If a synonym is found, append it to the transformed result
        if [[ "$synonym" != "null" && ! -z "$synonym" ]]; then
            transformed_result="$transformed_result $synonym"
        else
            # If no synonym is found, use the original word
            transformed_result="$transformed_result $word"
        fi
    done

    # Trim leading and trailing spaces and echo the result
    echo "$transformed_result" | sed 's/^ *//;s/ *$//'
}

# Usage
original_text="Hello, world! This is an example."
transformed_result=$(transform_text "$original_text")
echo "$transformed_result"  # Expected Output: "hi nature whatever iee autonomic nervous system representative"

Examples

ltrim: ltrim "   Hello World"
rtrim: rtrim "Hello World     "
trim: trim "  Hello World   "
uppercase: uppercase "hello world"
lowercase: lowercase "HELLO WORLD"
substitute: substitute "hello world" "o" "a"
capitalize: capitalize "hello world"
rot13: rot13 "hello world"
index: index "hello world" "o"
join: join "," "one" "two" "three"
substring: substring "hello world" 3 5
repeat: repeat "hello" 3
lastindex: lastindex "hello world" "o"
reverse: reverse "hello world"
shuffle: shuffle "hello world"
random_string: random_string 10
count: count "hello world" "l"
split: split "hello,world" ","
truncate: truncate "hello world" 5
sanitize: $(sanitize "$input" "$allowed")
parse_csv: $(parse_csv "$file" "$delimiter")
check_password_strength: check_password_strength "$password"
replace: $(replace "apple" "banana" "I like apple and apple pie.")
count_words: $(count_words "Hello, how are you?")
remove_special_chars: $(remove_special_chars "Hello, @world!")
reverse_words: $(reverse_words "This is a sentence.")
strip_html_tags: $(strip_html_tags "<p>This is <b>bold</b> text.</p>")
camel_to_snake_case: $(camel_to_snake_case "camelCaseString")
count_occurrences: $(count_occurrences "apple" "I like apple and apple pie.")
transform_text: $(transform_text "$original_text")

With these custom string functions, you can perform various string operations in your Bash scripts. You can also modify these functions to suit your specific needs. By creating custom string functions, you can save time and reduce code duplication in your Bash scripts.

...
Get Yours Today

Discover our wide range of products designed for IT professionals. From stylish t-shirts to cutting-edge tech gadgets, we've got you covered.

Explore Our Collection 🚀


See Also

comments powered by Disqus