Linux bash длина строки

How to Find Length of String in Bash [Quick Tip]

Here are various ways to calculate the length of a string in bash scripts.

If you are dealing with strings in bash, you may need to know the length of string.

Thankfully, getting length of string in bash is super simple. Let’s say you have a string named my_string . Its length can be extracted as:

Here’s an example to explain things better:

[email protected]:~$ my_string="abhishek" [email protected]:~$ echo "length is $" length is 8

That was easy, wasn’t it? You can save this string length to another variable and use it later:

[email protected]:~$ my_string="abhishek" [email protected]:~$ length=$ [email protected]:~$ echo "String length is $length" String length is 8

Like most other things in Linux, this is not the only way to calculate the length of strings in Bash.

Get string length in bash using expr command

Let’s see some other commands that could help you to test the string length in bash.

One of these commands is the expr command. It has several options that are useful for string options. Among them, length gives you the length of a string.

Since the expr command outputs the length, you should store it in a variable using command substitution.

#!/bin/bash str="my string" length=$(expr length "$str") echo "Length of my string is $length"

Now if you run this bash shell script, it will print the length:

[email protected]:~$ bash string.sh Length of my string is 9 

Use awk to get length of string

AWK is super versatile command for editing text in Linux command line. You can use it to calculate the string length as well.

You’ll have to use echo command and then use pipe redirection to parse it with awk:

As you can see, unless you are familiar with awk command basics, it’s not easy to remember the syntax.

Using wc command to calculate string length

Another way to get string length in Linux is using the wc command. Now wc command is used for counting number of lines, characters in a file.

You can echo the string and pipe it to wc command. The -m option gives the character count.

Notice the -n option with echo command? That is important because echo automatically adds a new line character \n at the end and it will increase the length of the string by one. With -n option, echo command doesn’t add new line character.

You can use command substitution to store the string length in a variable as you saw in previous examples.

#!/bin/bash str="my string" length=$(echo -n "my string" | wc -m) echo "Length of my string is $length"

Personally, $ is my preferred way of getting string length. Easier to remember.

Читайте также:  Как посмотреть в linux интерфейс

How about you? Which method do you prefer?

Источник

Find Length of String in Bash

The total number of characters of any string data indicates the length of the string. When we work with string data then it is important to count the length of the string for various programming tasks. The built-in function exists to count the total number of characters in many programming languages. But bash has no this type of built-in function. The length of the string can be counted in bash in multiple ways. How you can find out the length of a string data in bash is shown in this tutorial by using different examples.

Syntax:

Any of the following syntaxes can be followed to count the length of string.

$ <#strvar>
expr length $strvar
expr “ $ ”:’. * ’
echo $strvar | wc -c
echo $strvar | awk »

The above syntaxes show that length of the string can be counted by any bash command or without any command. ‘#‘ symbol can be used to count the length of the string without using any command. `expr` command can be used by two ways to count the length of a string. Without `expr`, `wc` and `awk` command can also be used to count the length of a string. The uses of the mention commands and ‘#’ symbol for counting the length of the string is shown in the next part of this tutorial.

Example-1: Using the‘#’ symbol to count the length of a string

The most commonly used and simple way to count the length of a string is to use “#” symbol. The following commands will assign a value to the variable, $string and print the total number of characters of $string.

The following output will appear after running the above command.

Example-2: Using `expr` to count the length of a string

Another way to count the length of a string is to use `expr` command with length keyword. The following commands will assign a value to the variable, $string, store the length value to the variable, $len and print the value of $len.

$ string = «Hypertext Markup Language»
$ len = ` expr length » $string » `
$ echo «The length of string is $len «

The following output will appear after running the above command.

Create a bash file named “len1.sh” and add the following script. Here, a string value will be taken from the user and the length of the string value will be counted by using `expr` command that will be printed later.

#!/bin/bash
echo “Enter a string:”
read strval
len = ` expr » $strval » : ‘.*’ `
echo «The length of the input string is $len «

Here, “I like Programming” is taken as input and the length of the string is 18.

Example-3: Using `wc` to count the length of the string

Create a bash file named “len2.sh” and add the following script. This script will read the first command-line argument into the variable $strval and count the length of $strval by using `wc` command that will be printed later.

#!/bin/bash
strval = $1
len = ` echo $strval | wc -c `
echo «The length of the first command-line argument is $len «

Run the script with one command-line argument.

The length of “Hello World” is 12 that is printed as output.

Читайте также:  Apt get install util linux

Example-4: Using `awk` to count the length of string

Create a bash file named “len3.sh” and add the following script. Here, the username will be taken as input and check the length of $username is less than 6 or not. If the length is less than 6 then the output will “Invalid username” otherwise the output will “Valid username”.

#!/bin/bash
echo «Enter the username»
read username
len = ` echo $username | awk » `
if [ $len -lt 6 ] ; then
echo «Invalid username»
else
echo «Valid username»
fi

Here, when “fahmida” is taken as the username then it is valid and when “lily” is taken as the username then it is invalid.

Conclusion:

Different ways of counting the length of a string in bash are shown in this tutorial by using various examples. The user can apply any of the mentioned ways to find out the length of the string.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Get Length of String in Bash

Get Length of String in Bash

  1. String Length and Basic Notations
  2. Use the # Operator to Calculate String Length in Bash
  3. Use the expr Command to Calculate String Length in Bash
  4. Use the awk Command to Calculate String Length in Bash
  5. Use the wc Command to Calculate String Length in Bash
  6. Calculate Character Length of a File

In programming languages, the length or size of the data type plays an important role. It helps in list traversals and facilitates the extraction of useful information.

The length is particularly important to perform tasks that require traversing the entire string. Therefore, keeping the importance of the length or size of any data type in view, we will learn different ways to calculate the string length.

String Length and Basic Notations

A string is the sequence of the different char , which may include the spaces. In Bash, the length of the string is the total number of chars in that string.

For example, the «Hello World» string contains ten char and one space. Therefore, its length is eleven.

Most scripting and programming languages have built-in or library functions for finding the length of the string. Similarly, there are many ways to manipulate Bash commands to calculate the string length in Bash.

Use the # Operator to Calculate String Length in Bash

We can use the # operator to calculate the length of the string. The following code shows the syntax to get the length of a string using the # operator.

First, we wrapped the variable containing the string with the curly brackets and preceded the # operator with the variable.

The # operator plays an essential role in printing the length of the string. If # is not used, the code will print the whole string, so adding it to the variable is essential.

Moreover, the $ sign outside will treat the string length as a variable and print it on the screen using the echo command. The following code shows the string’s length calculation using the # .

var="hello world" echo $var> echo $var> 

string length using hash

In line #1, we create the variable named var . The var variable can contain any string from the terminal or file string.

The second line prints the whole string using the $ and curly brackets. In the last line, we used the # symbol with the variable and got the length of the string printed on the command console.

Use the expr Command to Calculate String Length in Bash

Here, we will explore calculating the length of the string using the expr command. The following code depicts the basic syntax to use the expr command.

The expr command takes two parameters: before and after the comparison operator : . The comparison operator compares two strings for common characters and returns the number of similar chars .

In var1 , we give the string whose length needs to be calculated. The var2 contains a regular expression that parses the string one by one, and the comparison operator can calculate the count of each similar char .

The following code demonstrates an example.

var="hello world" echo `expr "$var" : ".*"` 

length using exp

In the above code, we assigned the string «hello world» to the variable var . The .* will parse all characters of the previous token (i.e., the value of var ).

Therefore, having two same operands, the comparison operator returns the total count of chars in the first operand.

Use the awk Command to Calculate String Length in Bash

Let’s calculate the string length using the awk command. The awk command is a scripting language used for data manipulations and report generation.

The following code demonstrates the string’s length calculation using the awk command.

var="hello world" n1=`echo $var |awk ''` echo $n1 

In the above code, we have used the built-in attribute of the awk and the print command.

The awk command takes the input of the string from the var variable using the pipe. The pipe sends the command output to the input after the pipe.

Line #3 prints the length of the string as a confirmation.

Use the wc Command to Calculate String Length in Bash

Now we will explore the string’s length calculation using the wc command. We only pass the string to the wc using the pipe with the flag -c or -m , and we will get the required output (i.e., length of the string).

The following Bash commands show the string length using the wc command.

The above code shows the string’s length calculation using two different flags of the wc command.

If we use only the wc command, it gives more information than the length of the string, which is not required. So, mentioning the flag after the wc command is inevitable.

We can use both flags, -c or -m . Both return the same output.

The following snippet shows the output of the above-described wc code.

length using the wc

Calculate Character Length of a File

Now we will explore how to calculate the string length from the file. We will create the file with the name abc.txt and write some text.

Then we will read and print the string’s length from the file.

The following code shows the calculation of the string length from the file.

touch abc.txt echo "hello world">> abc.txt cat abc.txt | wc -c 

The touch creates a new file, abc.txt , to which we write a hello world string using simple I/O redirection. The cat command on the third line displays the contents of abc.txt .

However, the pipe | makes the output of the cat command input to the wc command. Therefore, the wc will count words in this output.

Related Article — Bash String

Copyright © 2023. All right reserved

Источник

Оцените статью
Adblock
detector