- How to Find Length of String in Bash [Quick Tip]
- Get string length in bash using expr command
- Use awk to get length of string
- Using wc command to calculate string length
- 6 Wc Command to Count Number of Lines, Words, and Characters in File
- wc Command Syntax
- 1. A Basic Example of WC Command
- 2. Count Number of Lines in a File
- 3. Count Number of Words in a File
- 4. Count Number of Characters in a File
- 5. Count Number of Bytes in a File
- 6. Display Length of Longest Line in File
- 7. Check wc Command Options
- Команда wc в Linux
- Синтаксис команды wc
- Применение команды wc
- Вывод
- wc Linux Command with Examples
- Linux wc Command Syntax
- Linux wc Command Options
- Linux wc Examples
- Use wc with the find Command
- Show Stats for a List of Files
- Use wc to Count Files and Directories
- Perform wc Counts Across Multiple Files
- Find the Longest Line in All the Files
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.
How about you? Which method do you prefer?
6 Wc Command to Count Number of Lines, Words, and Characters in File
wc (short for word count) is a command line tool in Unix/Linux operating systems, which is used to find out the number of newline count, word count, byte and character count in the files specified by the File arguments to the standard output and hold a total count for all named files.
When you define the File parameter, the wc command prints the file names as well as the requested counts. If you do not define a file name for the File parameter, it prints only the total count to the standard output.
In this article, we will discuss how to use the wc command to calculate a file’s newlines, words, characters, or byte count with practical examples.
wc Command Syntax
The syntax of the wc command is shown below.
The followings are the options and usage provided by the wc command.
- wc -l – Prints the number of lines in a file.
- wc -w – prints the number of words in a file.
- wc -c – Displays the count of bytes in a file.
- wc -m – prints the count of characters from a file.
- wc -L – prints only the length of the longest line in a file.
Let’s see how we can use the ‘wc‘ command with the few available arguments and examples in this article. We have used the ‘tecmint.txt‘ file for testing the commands.
Let’s find out the output of the tecmint.txt file using the cat command as shown below.
$ cat tecmint.txt Red Hat CentOS AlmaLinux Rocky Linux Fedora Debian Scientific Linux OpenSuse Ubuntu Xubuntu Linux Mint Deepin Linux Slackware Mandriva
1. A Basic Example of WC Command
The ‘wc‘ command without passing any parameter will display a basic result of the ‘tecmint.txt‘ file. The three numbers shown below are 12 (number of lines), 16 (number of words), and 112 (number of bytes) of the file.
$ wc tecmint.txt 12 16 112 tecmint.txt
2. Count Number of Lines in a File
Count the number of newlines in a file using the option ‘ -l ‘, which prints the number of lines from a given file. Say, the following command will display the count of newlines in a file.
In the output, the first field is assigned as count and the second field is the name of the file.
$ wc -l tecmint.txt 12 tecmint.txt
3. Count Number of Words in a File
The -w argument with the wc command prints the number of words in a file. Type the following command to count the words in a file.
$ wc -w tecmint.txt 16 tecmint.txt
4. Count Number of Characters in a File
When using option -m with the wc command will print the total number of characters in a file.
$ wc -m tecmint.txt 112 tecmint.txt
5. Count Number of Bytes in a File
When using option -c will print the number of bytes of a file.
$ wc -c tecmint.txt 112 tecmint.txt
6. Display Length of Longest Line in File
The ‘wc‘ command allows an argument ‘ -L ‘, it can be used to print out the length of the longest (number of characters) line in a file.
So, we have the longest character line (‘Scientific Linux‘) in a file.
$ wc -L tecmint.txt 16 tecmint.txt
7. Check wc Command Options
For more information and help on the wc command, simply run the ‘ wc —help ‘ or ‘ man wc ‘ from the command line.
Usage: wc [OPTION]. [FILE]. or: wc [OPTION]. --files0-from=F Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of characters delimited by white space. With no FILE, or when FILE is -, read standard input. The options below may be used to select which counts are printed, always in the following order: newline, word, character, byte, maximum line length. -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts --files0-from=F read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input -L, --max-line-length print the maximum display width -w, --words print the word counts --help display this help and exit --version output version information and exit GNU coreutils online help: Full documentation at: or available locally via: info '(coreutils) wc invocation'
In this article, you’ve learned about the wc command, which is a simple command-line utility to count the number of lines, words, characters, and byes in text files. There are lots of such other Linux commands, you should learn and master your command-line skills.
Команда wc в Linux
Анализ файлов — неотъемлемая часть работы с ними. Иногда возникает необходимость подсчитать количество строк или слов в тексте. С этой задачей эффективно справляется команда wc Linux.
Утилита устанавливается по умолчанию практически во всех дистрибутивах GNU/Linux. В этой статье рассмотрим её функции и применение на практике.
Синтаксис команды wc
Для запуска утилиты откройте терминал и введите:
Терминал будет ожидать ввода данных. После нажатия комбинации клавиш Ctrl + D командный интерпретатор завершит работу программы и выведет три числа, обозначающих количество строк, слов и байт введённой информации.
Утилита может обрабатывать файлы. Стандартная инструкция выглядит так:
Программа также может принимать параметры для анализа отдельных значений. Наиболее используемые из них приведены в таблице ниже:
Параметр | Длинный вариант | Значение |
-c | —bytes | Отобразить размер объекта в байтах |
-m | —count | Показать количесто символов в объекте |
-l | —lines | Вывести количество строк в объекте |
-w | —words | Отобразить количество слов в объекте |
Под объектом следует понимать файл или данные, полученные на стандартный поток ввода.
Команда может обработать несколько файлов, если указать их через пробел или выбрать по шаблону.
Применение команды wc
Обработка стандартного потока ввода с завершением через Ctrl + D:
Согласно анализу, было введено 4 строки, содержащих 5 слов, объёмом в 35 байт.
Перенаправление потока вывода на вход wc:
Обработка всех файлов с расширением .sh в текущем каталоге:
В конце выводится итоговая информация, суммирующая значения для каждого столбца.
Выведем только количество символов и строк двух файлов:
Обратите внимание: порядок указания параметров не влияет на итоговый вид информации. Программа всегда выводит данные в виде СТРОК — СЛОВ — БАЙТ (СИМВОЛОВ) [— ФАЙЛ]. Если какой-то параметр будет отсутствовать, его столбец просто проигнорируется, не задевая остальные. Количество символов будет стоять первым, если в команде содержался и вывод байт.
Вывод
Команда wc Linux является эффективным инструментом при анализе файлов в GNU/Linux. Она может обрабатывать как стандартный поток ввода, так и несколько файлов одновременно. Для извлечения конкретных данных используются параметры командной строки.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
wc Linux Command with Examples
The wc command is a part of the coreutils Linux package containing the GNU core utilities. Use wc to count the number of characters, words, lines, and bytes in a file or standard input.
This tutorial will provide details about the wc command and its options. The article also includes helpful examples to demonstrate how wc works together with other commands.
Linux wc Command Syntax
The wc command takes the following syntax:
By default, the output shows the number of new lines, words, and bytes in a file, followed by the file name.
To view stats for multiple files, list the files in a single command:
wc [options] [location/file1] [location/file2] [location/file3]
The output shows the information for each file, followed by the total number of lines, words, and bytes.
Use input redirect to stop wc from printing the file name:
Alternatively, use the cat command to list the contents of the file, then pipe the output to wc :
Linux wc Command Options
The wc command takes the following options:
Option | Description |
---|---|
-c, —bytes | Print the number of bytes. |
-m, —chars | Print the number of characters. |
-l, —lines | Print the number of lines. |
—files0-from=[file] | Read the input from the files specified by NUL-terminated names in the file. If — is provided instead of the file, the command reads from standard input. |
-L, —max-line-length | Print the length of the longest line. |
-w, —words | Print the number of words. |
—help | Show help. |
—version | Show version information. |
Linux wc Examples
The examples below illustrate the use of the wc command.
Use wc with the find Command
Use the find command to provide output for wc . The example below lists the number of characters for each file in the /etc folder whose filename starts with 30 :
find /etc -name '30*' -print0 | wc -m --files0-from=-
The output of find is piped to wc , which then outputs the relevant stats.
Show Stats for a List of Files
The wc command can read from a file with file names to provide the stats for each file in the list. For wc to be able to read the file correctly, the names in the file need to be NUL-terminated.
Note: A NUL-terminated string is a string that ends with a null-char, the character whose all bits are zero.
Use find to create a file containing a NUL-terminated list of files located in the current directory:
The following command reads the file and provides the byte count for each of the files:
Use wc to Count Files and Directories
To find the number of files and directories in the current directory, pipe the ls command to wc :
The -l option counts the number of lines in the ls output. This number corresponds to the total number of files and directories.
Perform wc Counts Across Multiple Files
Use wc to count characters, words, lines, and bytes across multiple files. For example, to see the total word count of every TXT file in a directory, type:
The cat command pipes to wc the contents of all the TXT files in the directory. wc -w counts the total number of words.
Find the Longest Line in All the Files
The -L option prints the length of the longest line for each file. If more than one file is specified, the total row shows the longest line across all files.
For example, to find the longest line in all the TXT files in a directory, type:
wc processes the TXT files and, for each file, prints the number of characters in the longest line.
The last row shows the character count of the longest line in all the files.
This tutorial presented the wc command and its options. You also learned how wc works in conjunction with other Linux commands.
Refer to the Linux Commands Cheat Sheet article for more command examples.