Summary of several methods for shell to get string length



In our daily work, string operation is very common in shell scripts, and there are many ways to achieve it. Here are a few possible ways to find strings. Let’s have a look at the detailed introduction.

The method is as follows:

[method 1]: use ${ා STR} to get the length of the string

[method 2]: using the length method of awk


1) it is better to use {} to place variables

2) it can also be usedlength($0)To count the length of each line in the file

[method 3]: use NF term of awk to get string length

Remarks:-F is the separator, NF is the number of fields, that is, the length of a single line string

[method 4]: use the – L parameter of WC to get the length of string

Remarks:-L parameter

1) for multi line files, it means the length of the longest line to be printed! 82, indicating that the maximum line length of the / etc / passwd file is 82

2) For a single line string, the length of the current line string!

[method 5]: using the – L parameter of WC and echo – n parameter


1) – C parameter: count the number of characters

2) – n parameter: remove the “\ n” line break. If it is not removed, the default is line break. The number of characters is 7

[method 6]: using the length method of expr

[method 7]: using expr’s $STR: “. *” technique

Remarks:. * stands for any character, that is, any character is used to match the string, and the result is to match to 6 characters, that is, the length of the string is 6


The above is the whole content of this article. I hope that the content of this article can bring some help to your study or work. If you have any questions, you can leave a message and communicate with us. Thank you for your support for developpaer.

Recommended Today

Application of tree

Application of tree Storage structure of tree Parental representation (sequential storage) Definition: in each node, the “pointer” (position subscript) pointing to the parents is saved. The root node is fixedly stored in 0, – 1 indicates that there are no parents. Add: add directly without following the logical order. Delete: ① set the pointer to […]