Solved

Find a pattern in a variable

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Little introduction about CP: CP is a command on linux that use to copy files and folder from one location to another location. Example usage of CP as follow: cp /myfoder /pathto/destination/folder/ cp abc.tar.gz /pathto/destination/folder/ab…
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…
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
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.

831 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