Solved

Find a pattern in a variable

Posted on 2008-10-19
2
652 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

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 …
Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

914 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

12 Experts available now in Live!

Get 1:1 Help Now