Find a pattern in a variable

Posted on 2008-10-19
Last Modified: 2013-12-26
Can anyone tell me how to find a pattern in a string of text in a variable using Bash in Linux?

var=Line 1: This is a line

I want to be able to search var to determine if : is part of the text.  If var does contain ":", I would like to be able to split it so that I can assign Line 1 to var1 and This is a line to var2.
Question by:doug5516
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 40

Expert Comment

ID: 22755249

line=`grep "var=" file`
echo $line | grep ":"
if [ $? -eq 0 ]
      var2=`echo $line | awk -F":" '{ print $2 }'`
      var=`echo $line | awk -F"=" '{ print $2 }'`
LVL 48

Accepted Solution

Tintin earned 500 total points
ID: 22755487
If you have bash, you might as well use it rather than call external utilities.
var='Line 1: This is a line'
if echo $var | grep -q  :

Open in new window


Featured Post

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

SSH (Secure Shell) - Tips and Tricks As you all know SSH(Secure Shell) is a network protocol, which we use to access/transfer files securely between two networked devices. SSH was actually designed as a replacement for insecure protocols that sen…
Linux users are sometimes dumbfounded by the severe lack of documentation on a topic. Sometimes, the documentation is copious, but other times, you end up with some obscure "it varies depending on your distribution" over and over when searching for …
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question