Solved

Find a pattern in a variable

Posted on 2008-10-19
2
651 Views
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?

Example:
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.
0
Comment
Question by:doug5516
2 Comments
 
LVL 40

Expert Comment

by:omarfarid
ID: 22755249
try

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

Accepted Solution

by:
Tintin earned 500 total points
ID: 22755487
If you have bash, you might as well use it rather than call external utilities.
#!/bin/bash

var='Line 1: This is a line'
 

if echo $var | grep -q  :

then

   var1=${var%%:*}

   var2=${var#*:}

fi

Open in new window

0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

The purpose of this article is to demonstrate how we can use conditional statements using Python.
It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now