Searching for pattern in variable using case statements


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Searching for pattern in variable using case statements
# 1  
Old 07-24-2016
Searching for pattern in variable using case statements

i would like to search a variable for a pattern, without having make any calls to external tools.

i have a code like this:

Code:
COUNTPRO2="gine is very bad
vine is pretty good"

case "${COUNTPRO2}" in
*vine*)
    factor=${COUNTPRO2}
    echo $factor
;;
esac

If the variable contains a specific pattern, i.e. in this case "vine", then i want the case statement to output ONLY the line containing the pattern..i.e.

Code:
vine is pretty good

is this possible?

what i was doing before was:

Code:
factor=$(echo "${COUNTPRO2}" | egrep vine)

I would like to avoid calling the egrep.

the solution needs to be portable as i intend to use it on linux, aix and sunos

Last edited by SkySmart; 07-24-2016 at 12:49 PM..
# 2  
Old 07-24-2016
Hi.

It would probably be useful if you were to tell us which items the different platforms had in common: bash, ksh, zsh, awk, perl, grep, etc.

Here's a solution using an array, loop, and case:
Code:
#!/usr/bin/env bash

# @(#) s1       Demonstrate shell array with case selector.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { : ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
C=$HOME/bin/context && [ -f $C ] && $C

v1="gine is very bad
vine is pretty good"

pl " Input data variable, piped into cat:"
echo "$v1" | cat -n

pl " Input data array with printf:"
declare -a a1="$v1"
printf "%s\n" "${a1[*]}"

pl " Looking through each element in the array:"
IFS=$'\n'
for line in ${a1[*]}
do
  db " Working on line [$line]"
  case $line in
  (*vine*)      echo " HIT! Found vine." ;;
  esac
done

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.4 (jessie) 
bash GNU bash 4.3.30

-----
 Input data variable, piped into cat:
     1  gine is very bad
     2  vine is pretty good

-----
 Input data array with printf:
gine is very bad
vine is pretty good

-----
 Looking through each element in the array:
 db,  Working on line [gine is very bad]
 db,  Working on line [vine is pretty good]
 HIT! Found vine.

See man bash, etc. for details.

Best wishes ... cheers, drl
This User Gave Thanks to drl For This Post:
# 3  
Old 07-24-2016
Quote:
Originally Posted by drl
Hi.

It would probably be useful if you were to tell us which items the different platforms had in common: bash, ksh, zsh, awk, perl, grep, etc.

Here's a solution using an array, loop, and case:
Code:
#!/usr/bin/env bash

# @(#) s1       Demonstrate shell array with case selector.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { : ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
C=$HOME/bin/context && [ -f $C ] && $C

v1="gine is very bad
vine is pretty good"

pl " Input data variable, piped into cat:"
echo "$v1" | cat -n

pl " Input data array with printf:"
declare -a a1="$v1"
printf "%s\n" "${a1[*]}"

pl " Looking through each element in the array:"
IFS=$'\n'
for line in ${a1[*]}
do
  db " Working on line [$line]"
  case $line in
  (*vine*)      echo " HIT! Found vine." ;;
  esac
done

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.4 (jessie) 
bash GNU bash 4.3.30

-----
 Input data variable, piped into cat:
     1  gine is very bad
     2  vine is pretty good

-----
 Input data array with printf:
gine is very bad
vine is pretty good

-----
 Looking through each element in the array:
 db,  Working on line [gine is very bad]
 db,  Working on line [vine is pretty good]
 HIT! Found vine.

See man bash, etc. for details.

Best wishes ... cheers, drl
they have awk in common.
# 4  
Old 07-24-2016
What about a while loop?

Code:
COUNTPRO2="gine is very bad
vine is pretty good"

echo "${COUNTPRO2}" | while read line; do
        [[ $line == *"vine"* ]] && echo $line
done

This User Gave Thanks to pilnet101 For This Post:
# 5  
Old 07-24-2016
Quote:
Originally Posted by pilnet101
What about a while loop?

Code:
COUNTPRO2="gine is very bad
vine is pretty good"

echo "${COUNTPRO2}" | while read line; do
        [[ $line == *"vine"* ]] && echo $line
done


this seems to do precisely what i needed. not sure how much time it'll save as oppose to calling grep for each pattern i'm searching for.
# 6  
Old 07-24-2016
It would all depend upon the number of lines the code is traversing.
# 7  
Old 07-24-2016
You could also try:
Code:
#!/bin/ksh
COUNTPRO2="gine is very bad
vine is pretty good"

while IFS= read -r factor
do	case "$factor" in
	(*vine*)printf '%s\n' "$factor"
		;;
	esac
done <<EOF
$COUNTPRO2
EOF

Note that I used printf instead of echo because the output you get from echo might not be what you want if a line in the expansion of $COUNTPRO2 starts with a hyphen or contains any backslash characters. And, using a here-document instead of an array makes it portable to many more shells.

Forking and execing an external utility is a VERY slow operation when compared to the actions required to perform a case statement pattern match.

Although the above was written and tested using a Korn shell, this should work with any shell that is based on Bourne shell syntax (including a 1970's vintage pure Bourne shell).
These 2 Users Gave Thanks to Don Cragun For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Convert to case statements from if/elif

Hello, I wrote the case on code but it mistakes. I am not sure. If/elif code: #!/bin/ksh you=$LOGNAME hour=`date | awk '{print substr($4, 1, 2)}'` print "The time is: $(date)" if (( hour > 0 && $hour < 12 )) then print "Good morning, $you!" elif (( hour == 12 )) then (7 Replies)
Discussion started by: Masterpoker
7 Replies

2. Shell Programming and Scripting

Ignore case in awk while pattern searching

Hi , I have the file where i have to search for the pattern. The pattern may be lower case or upper case or camel case. Basically I want to ignore while searching the pattern in awk. awk '/error|warning/exception/' filename Please help me (3 Replies)
Discussion started by: arukuku
3 Replies

3. Homework & Coursework Questions

Case statements and creating a file database

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: The assignment is posted below: Maintain automobile records in a database Write a shell script to create,... (1 Reply)
Discussion started by: Boltftw
1 Replies

4. Shell Programming and Scripting

Not able to exit from case statements

Hi all, I wrote the following simple shell script to perform addition, subtraction, multiplication and division. In the below program, i am not able to exit from the script Shell Script ----------- #!/bin/sh bgcal() { cal="" echo "Enter the Option Number: \c" read cal if then... (3 Replies)
Discussion started by: uxpassion
3 Replies

5. UNIX for Dummies Questions & Answers

How to combine case statements

Hi, I need to change military time to regular time. I know to use case to indicate whether a.m. or p.m. as follows: case "$hour" in 0? | 1 ) echo a.m.;; 1 ) echo p.m.;; * ) echo p.m.;; esac My question is how do I add the hour and minute... (2 Replies)
Discussion started by: karp3158
2 Replies

6. Shell Programming and Scripting

how to convert value in a variable from upper case to lower case

Hi, I have a variable $Ctrcd which contains country names in upper case and i want to convert them into lower case. I have tried so many solutions from already existing threads but couldn't get the correct one. Can anybody help me with this..... Thanks a lot.. (2 Replies)
Discussion started by: manmeet
2 Replies

7. Shell Programming and Scripting

Problem with my case statements

Hi there, Im having some problems with this function, I pass two arguments to the function $1 $2 (Arguments are month and date inputted by the user) for some reason the case always fails... however in the cases defined below where it shouldnt fail the result is: if it fails with input... (6 Replies)
Discussion started by: Darklight
6 Replies

8. Shell Programming and Scripting

Major Awk problems (Searching, If statements, transposing etc.)

Please bare with me as task is very detailed and I'm extremely new to Awk/sed. Keep in mind I'm running windows so I'm using a dos prompt The attachment is a server report that I'm trying to manipulate with little success. For each server, I need to take the most recent information about them... (2 Replies)
Discussion started by: Blivo
2 Replies

9. Shell Programming and Scripting

case statements

i need to use a case statement to do something when the user enters nothing at the prompt. i know about the if statement and that isnt' what i'm interested in using for this. i want to use case. heres the scenerio. a program asks a user for an input. i want to use a case statement to... (1 Reply)
Discussion started by: Terrible
1 Replies

10. UNIX for Dummies Questions & Answers

Pattern searching inside Variable - not looking at files

Hi, I've searched this site and not found this already, so if I missed on my search, sorry. I need to pass in a variable to a script, where the first three characters of that variable represent a calendar quarter, and the last 2 characters are the year. I.E. Q0105 for Q1, Q0205 for Q2, and... (3 Replies)
Discussion started by: Rediranch
3 Replies
Login or Register to Ask a Question