Linux bash string concatenation

Конкатенация строк в Bash

Одна из наиболее часто используемых строковых операций — это конкатенация. Конкатенация строк — это просто причудливое программное слово для соединения строк путем добавления одной строки в конец другой строки.

В этом руководстве мы объясним, как объединять строки в Bash.

Объединение строк

Самый простой способ объединить две или более строковых переменных — записать их одну за другой:

Последняя строка будет отображать объединенную строку:

Вы также можете объединить одну или несколько переменных с помощью буквальных строк:

В приведенном выше примере переменная VAR1 заключена в фигурные скобки, чтобы защитить имя переменной от окружающих символов. Если за переменной следует другой допустимый символ имени переменной, вы должны заключить его в фигурные скобки $ .

Чтобы избежать проблем с разделением слов или подстановкой слов, вы всегда должны стараться заключать имя переменной в двойные кавычки. Если вы хотите подавить интерполяцию переменных и особую обработку символа обратной косой черты вместо двойных, используйте одинарные кавычки.

Bash не разделяет переменные по «типу», переменные обрабатываются как целые или строковые в зависимости от контекстов. Вы также можете объединять переменные, содержащие только цифры.

Объединение строк с помощью оператора + =

Другой способ объединения строк в bash — это добавление переменных или буквальных строк к переменной с помощью оператора += :

В следующем примере оператор += для объединения строк в цикле bash for :

Выводы

Объединение строковых переменных — одна из самых фундаментальных операций в сценариях Bash. После прочтения этого руководства вы должны хорошо понимать, как объединять строки в Bash. Вы также можете ознакомиться с нашим руководством по сравнению строк .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How To Bash Concatenate or Add Strings?

Bash provides string operations. We can use different operations like remove, find or concatenate strings in bash. In this tutorial we will look how to add or concatenate strings in Linux bash.

Put Variables Side By Side

The simplest and easy to understand way to concatenate string is writing the variables side by side. We will write the variables like $a$b . We do not need extra operater or function to use. In this example we will concatenate two variables named $a and $b into $c .

Put Variables Side By Side

Читайте также:  Hp truevision hd windows 10 не работает

Double Quotes

Other useful alternative is using string variables inside strings which is defined with double quotes. We will put the variables name into double quotes with soe string. In this example we will put variable name $a into string Welcome

Double Quotes

Append Operator

Popular programming languages provides += compact add operator which is consist of plus and equal sign. We can add existing variable new string. This will add new string to the end of string variable. In this example variable named $a has all ready string value Welcome and we will add to poftut like below.

Append Operator

Printf Function

printf is a function used to print and concatenate strings in bash. We can provide the string we want to print into a variable. We will use -v option with the variable name and the string we want to add. In this example we will use string variable $a and to poftut .

Printf Function

Источник

Конкатенация строк Bash

Bash Concatenate Strings

В этом руководстве мы объясним, как объединять строки в Bash.

Одной из наиболее часто используемых строковых операций является конкатенация. Конкатенация строк — это просто причудливое программирующее слово для объединения строк путем добавления одной строки в конец другой строки.

Конкатенация строк

Самый простой способ объединить две или более строковые переменные — записать их одну за другой:

Последняя строка будет выводит:

Вы также можете объединить одну или несколько переменных с литеральными строками:

В приведенном выше примере переменная VAR1 заключена в фигурные скобки для защиты имени переменной от окружающих символов. Когда за переменной следует другой допустимый символ имени переменной, вы должны заключить его в фигурные скобки $ .

Чтобы избежать каких-либо проблем с разделением слов или глобализацией, всегда пытайтесь использовать двойные кавычки вокруг имени переменной. Если вы хотите подавить переменную интерполяцию и специальную обработку символа обратной косой черты вместо двойных, используйте одинарные кавычки.

Bash не разделяет переменные по «типу», переменные обрабатываются как целое число или строка в зависимости от контекста. Вы также можете объединить переменные, которые содержат только цифры.

Конкатенация строк с оператором + =

Другим способом объединения строк в bash является добавление переменных или литеральных строк к переменной с помощью += оператора:

В следующем примере используется += оператор для объединения строк в цикле bash for :

Вывод

Конкатенация строковых переменных является одной из самых фундаментальных операций в скриптах Bash. После прочтения этого урока вы должны хорошо понимать, как объединять строки в Bash. Вы также можете проверить наше руководство по сравнению строк .

Источник

Simple guide to concatenate strings in bash with examples

Table of Contents

How to concatenate strings with underscore, newline, whitespace or any other character in bash? How to append substrings in a string in bash or shell script? How to append starings in a variable using for loop with whitespace? Bash join strings with separator.

These are some of the common questions which we will address in this tutorial. concatenate means nothing but linking or putting things together in some sort of chain or series. You may choose to put two or multiple strings together by any separation character.

Читайте также:  Как установить все версии windows

Basic concatenation of two strings with no separator

This is quite a straight forward use case wherein we have two variables with some string and you want to concatenate them

For example, I have two variables:

As you have noticed VAR1 already contains an extra space so we are just printing both variables together, the output from this script would be:

Now we can also join VAR1 and VAR2 into a third variable VAR3 and the output would be the same i.e. » Hello World «

Join strings with special character as separator

Now the above was a very basic example, let’ take it to the next level. In this example we will concatenate strings with underscore, you may choose any other separator such as comma, whitespace, hyphen etc.

Using above script as an example, what would happen if I just place » _ » (underscore) between both the variables, it should work right?

Let’s check the output from this script:

From our output «Hello» is missing, WHY?

Because bash considered $VAR_ as one variable and $VAR2 as second. Since $VAR_ doesn’t exist so Hello is missing. So in such case always use curly braces to denote a variable when working with concatenation.

So as you see now I have used curly braces <> to make sure the separator is not considered part of the variable, now let’s check the output from the script:

This is the one of the most important thing you should always remember when working with bash string concatenation. Now you can use any other special character here to combine both the strings.

Concatenate in a loop (append strings to a variable)

Now assuming you have a requirement where in you have to test network connectivity of multiple hosts and then print a summary with list of success and failed hosts. This would require you to keep storing the list of success and failed hosts, this can be done using various methods but we will use += operator to store the list of strings in a variable (or convert to array based on your requirement)

In this example script I have defined a list of 4 hosts out of which 2 are reachable (yeah I know this already) while two are un-reachable but we will use a script to check this. Based on the ping output we will append the string in different variable

Output from this script:

Here if you notice this if condition is the main part which stores the server list. I have intentionally added an empty whitespace after $server so that there is a gap between list of servers when added to SUCCESS or FAILED

You may choose to strip the last whitespace character at the end of execution of that creates a problem in your output:

Concatenate strings using new line character

You can use the same operator += to append strings with new line character, although printing the output would require certain extra handling . In this example I have created an array with some values, I will iterate over these values and then join them together with a new line character at the end

Читайте также:  Сравнение оболочек linux mint

Output from this script:

So I have combined all the strings in a for loop (you can also use while or any other loop — doesn’t matter) using new line character. By default echo will not be able to understand » \n » and will consider it as a text so we use -e to enable interpretation of backslash escapes. The -n is used with echo to suppress the last line or you will have an extra new line in the end, you can also use printf to avoid all this additional argument.

Conclusion

In this tutorial we learned about bash string concatenation using different joining character such as whitespace, newline, special characters etc. You can use += operator in all sorts of scenarios to combine strings. But one thing to remember is that by default in a loop += will append the string in the end of variable, if you have a different requirement than that would need special handling.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Concatenate Strings in Bash

String concatenation is one of the most widely used operations in the programming, which refers to joining two or more strings by placing one at the end of another. To concatenate strings in Bash, we can write the string variables one after another or concatenate them using the += operator.

String Concatenation Placing One String Variable After Another

We can concatenate string by placing string variables successively one after another.

In the above example, we concatenate STR1 and STR3 and assign the concatenated string to STR3 . The double-quotes » » are used to prevent splitting or globbing issues.

We use the echo command to print the output.

Concatenate One or More Variables With Literal Strings

Here, <> is used to isolate the string variable from string literal.

It concatenates string variable STR1 with string literal -Stack .

Concatenate More Than Two Strings Together

We can place the string variables and literals successively to concatenate more than two string variables together.

Concatenate Numeric and String Literals

The variables are not differentiated by Bash based on the type while concatenating. They are interpreted as integer or string depending upon the context.

It concatenates string variable FIVE- and 5 together.

String Concatenation Using the += Operator

Bash also allows string concatenation using the += operator. Simply a+=b can be understood as a=a+b .

Here, STR2 is appended at the end of STR1 , and the result is stored in the STR1 variable.

To append multiple values, we can use a simple for loop.

Источник

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