Linux bash if string contains

Как проверить, содержит ли строка подстроку в Bash

Одна из наиболее распространенных операций при работе со строками в Bash — определить, содержит ли строка другую строку.

В этой статье мы покажем вам несколько способов проверить, содержит ли строка подстроку.

Использование подстановочных знаков

Самый простой подход — окружить подстроку символами подстановки звездочки (звездочкой) * и сравнить ее со строкой. Подстановочный знак — это символ, используемый для обозначения нуля, одного или нескольких символов.

Если тест возвращает true , подстрока содержится в строке.

В приведенном ниже примере мы используем оператор if и оператор равенства ( == ), чтобы проверить, найдена ли подстрока SUB в строке STR :

#!/bin/bash STR='GNU/Linux is an operating system' SUB='Linux' if [[ "$STR" == *"$SUB"* ]]; then echo "It's there." fi 

При выполнении скрипт выведет:

Использование оператора case

Вместо использования оператора if вы также можете использовать оператор case, чтобы проверить, включает ли строка другую строку.

#!/bin/bash STR='GNU/Linux is an operating system' SUB='Linux' case $STR in *"$SUB"*) echo -n "It's there." ;; esac 

Использование оператора Regex

Другой способ определить, встречается ли указанная подстрока в строке, — использовать оператор регулярного выражения =~ . Когда используется этот оператор, правая строка рассматривается как регулярное выражение.

Точка, за которой следует звездочка .* Соответствует нулю или более вхождений любого символа, кроме символа новой строки.

#!/bin/bash STR='GNU/Linux is an operating system' SUB='Linux' if [[ "$STR" =~ .*"$SUB".* ]]; then echo "It's there." fi 

Использование Grep

Команду grep также можно использовать для поиска строк в другой строке.

В следующем примере мы передаем строку $STR в качестве входных данных в grep и проверяем, найдена ли строка $SUB во входной строке. Команда вернет true или false в зависимости от ситуации.

#!/bin/bash STR='GNU/Linux is an operating system' SUB='Linux' if grep -q "$SUB"  "$STR"; then echo "It's there" fi 

Параметр -q указывает grep быть тихим и пропускать вывод.

Выводы

Проверка наличия в строке подстроки — одна из самых основных и часто используемых операций в сценариях Bash.

После прочтения этого руководства вы должны хорошо понимать, как проверить, включает ли строка другую строку. Вы также можете использовать другие команды, такие как awk или sed для тестирования.

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

Источник

Как в Bash проверить, содержит ли строка подстроку

Как в Bash можно протестировать, содержит ли она другую строку?

Рассмотрим сразу несколько вариантов, с использованием различных программ: какие-то будут быстрее или медленнее, какие-то решения будут работать только в Bash, а некоторые в любой оболочке Linux.

1.

Вариант с обрамлением строки подстановочными символами:

string='Моя длинная строка' if [[ $string == *"Моя длинная"* ]]; then echo "Подстрока найдена!" fi

Обратите внимание, что пробелы в искомой подстроке должны быть заключены в двойные кавычки, а звёздочки должны быть снаружи — в точности как на примере. Также обратите внимание, что используется простое сравнение (то есть ==), а не оператор регулярных выражений (то есть не =~).

Также не забывайте делать пробелы до и после квадратных скобок.

Если поменять строки местами, то для проверки поменяйте == на != и результат будет точно таким же.

2.

Вариант с регулярными выражениями

string=Моя строка'; if [[ $string =~ "Моя" ]] then echo "Подстрока найдена!" fi

Чтобы проверить, что строка НЕ содержит подстроку:

Пример выше вернёт true.

3.

Похожего эффекта можно добиться и с выражением case:

case "$string" in *foo*) # Do stuff ;; esac

Это решение является портативным на оболочки posix (то есть это не башизм).

4.

Следующая функция возвращает True или False в зависимости от того, содержит ли одна строка другую или нет. То есть эту

stringContain 'ИСКОМАЯ ПОДСТРОКА' 'БОЛЬШАЯ СТРОКА'
stringContain() < [ -z "$1" ] || < [ -z "$" ] && [ -n "$2" ];>;>; if stringContain 'bcd' 'abcdef'; then echo yes; else echo no; fi yes

Пример, когда подстрока не найдена:

stringContain() < [ -z "$1" ] || < [ -z "$" ] && [ -n "$2" ];>;>; if stringContain 'ddd' 'abcdef'; then echo yes; else echo no; fi yes

5.

Вы должны помнить, что сценарии оболочки — это не столько язык, сколько набор команд. Инстинктивно вы думаете, что этот «язык» требует, чтобы за if следовало [ или [[ с помощью которых выполняется тестирование. Обе они являются просто командами, которые возвращают состояние выхода, указывающее на успех или неудачу (как и любая другая команда). По этой причине я бы использовал grep, а не команду [.

Теперь, когда вы воспринимаете if как тестирование статуса выхода команды, которая следует за ним (завершена точкой с запятой), почему бы не пересмотреть источник строки, которую вы тестируете?

## вместо этого filetype="$(file -b "$1")" if grep -q "tar archive" 

Опция -q делает так, что grep ничего не выводит поскольку мы только хотим только код возврата

Можно использовать подстановку процесса:

Источник

How to Check if String Contains Substring in Bash

In Bash scripting, it's often necessary to check if a string contains a specific substring. This can be useful for validating user input, processing text data, or executing certain actions based on the presence or absence of a certain pattern.

The process of checking if a string contains a substring in bash can be done in several ways, including using the if statement alongside the [[ operator, or using the grep command.

In this article, we will be exploring both methods in detail, along with examples of how to implement them in your scripts. Whether you're a beginner or an experienced bash programmer, this guide will provide a comprehensive overview of how to check if a string contains a substring in bash.

Method 1: Using the if Statement and the [[ Operator

The if statement in Bash is used to perform conditional execution of commands based on the exit status of a test command. In this case, we can use the [[ operator to perform a string comparison between the target string and the substring.

Let's take a quick look at the syntax for using the if statement and the [[ operator to check if a string contains a substring:

if [[ "$string" == *"substring"* ]] then echo "Substring found." else echo "Substring not found." fi 

Here, $string is the target string that you want to check for the presence of a substring, and "substring" is the substring you're searching for. The * wildcard before and after the substring acts as a placeholder for any characters that may come before or after the substring.

Now, we can take a look at the actual example that checks if the string "This is a test string" contains a string "test" as its substring:

# Define the target string string="This is a test string." # Check if the string contains the substring "test" if [[ "$string" == *"test"* ]] then echo "Substring found." else echo "Substring not found." fi 

As expected, the if statement will return "Substring found." as the target string $string contains the substring "test" .

Now, let's take a look at the pros and cons of this method for checking if a string contains a substring in Bash.

Pros

  • Syntax is simple and easy to understand
  • Doesn't require an external tool or command
  • Processing time is faster than using the grep command

Cons

  • Limited in functionality, as it only checks for the presence of a substring and cannot be used for more advanced pattern matching

Method 2: Using the grep Command

The grep command is a powerful tool for searching for patterns in text data. It can be used to check if a string contains a substring by using the -q option to perform a quiet search, which returns an exit status based on whether or not the substring was found.

Take a look at the syntax for using the grep command to check if a string contains a substring:

if echo "$string" | grep -q "$substring" then echo "Substring found." else echo "Substring not found." fi 

As in the previous method, $string is the target string that you want to check for the presence of a substring, and $substring is the substring you're searching for. The echo command is used to pipe the target string to the grep command, which performs a quiet search for the specified substring.

Now, we can implement the previous example of checking the existence of the "test" substring inside of the "This is a test string." string:

Define the target string string="This is a test string." # Define the substring substring="test" # Check if the string contains the substring if echo "$string" | grep -q "$substring" then echo "Substring found." else echo "Substring not found." fi 

As we expected, the if statement will return "Substring found." as the target string $string definitely contains the substring "test" .

Pros

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  • More powerful and flexible than the if statement and [[ operator
  • Can be used for more advanced pattern matching and text processing tasks
  • Widely used and well-documented

Cons

  • Slower processing time compared to the if statement and [[ operator
  • Requires the use of an external command, which can add complexity to your script

When to Use Each Method

Use the if statement and [[ operator if you need to perform a simple check for the presence of a substring and don't require any advanced pattern matching capabilities. This method is suitable for simple use cases and is easy to understand and implement.

Use the grep command if you need to perform more advanced pattern matching and text processing tasks, or if you prefer a more flexible and powerful tool. This method is suitable for more complex use cases and is a good choice if you're familiar with the grep command.

All-in-all, the choice between the two methods depends on the specific needs of your script and your personal preference. Both methods have their own advantages and disadvantages, and it's up to you to choose the one that best fits your requirements.

Conclusion

In this article, we covered two methods for checking if a string contains a substring in Bash: using the if statement and the [[ operator, and using the grep command.

In conclusion, both methods have their advantages and disadvantages, and it's up to you to choose the one that best fits your requirements. If you're performing a simple check for the presence of a substring, the if statement and the [[ operator is a good choice. If you require more advanced pattern matching capabilities, the grep command is a better option.

In general, it's always a good idea to choose the simplest and most straightforward solution that meets your needs, as it will make your code easier to understand and maintain in the long run. Remember to consider your specific needs and choose the method that best fits your requirements.

Источник

Bash checking if string does not contain other string

It's a inversed duplicate: read this answer and use else or not like in: if ! stringContain "c0" "$myteststring" ;then .

3 Answers 3

if [[ $ != *"c0"* ]];then # testmystring does not contain c0 fi 

See help [[ for more information.

I agree they're superfluous for the mere example shown above. But if the variable name and the pattern string are getting more complex (e.g.: containing space in the pattern string), quoting them is necessary. Anyway, quoting them usually does no harm. 🙂

True it does no harm, and if you enjoy typing them then knock yourself out! Sorry, I know this is pedantic, its just that I find people often use things like < >by rote without understanding when they are needed and when they are not (I did upvote you).

@cdarke: as far as i know not using <> incurs in a performance penalty because the shell cannot immediately assume it is a variable while with it, it can. I am not completely absolutely sure and worse i cant remember where I saw the numbers.

@Randyman99: while I agree with your aim, I don't believe that adding superfluous characters when you don't understand what they do develops good programming practice. That's my point - too many people use them because of a cargo culture and they never learn what they are actually for - that's not good programming practice. Defensive programming is good, mindless programming is not good. Take that from someone who has been programming professionally for fifty years.

Источник

Читайте также:  Linux show path to directory
Оцените статью
Adblock
detector