Home > database >  Once you find match exit in shell script
Once you find match exit in shell script

Time:10-23

I'am working to find a match in text file from a shell script and get the desired output

the format of text file is like this :

    var1 = X
    var2 = X
    var3 = X
    var4 = BDH

My shell script is like this for now

    values=$(grep -hnr -A2 "$another_value_to_match" exemple.txt | cut -d "=" -f2)
    find_all_values=$(ls -d $DIR/["$values"]* | xargs -n 1 basename)

another_value_to_match is a variable i'am taking from another function and should contain (var1, var2, var3, var4). find_all_values is trying to look into a large folder for sub-folders that start with (X, or B or D or H).

My problem is that if another_value_to_match == var4 everything is fine and works correctly because it's the last line in the text file but if another_value_to_match == var1 or any other value I get as output : X X X BDH.

My question is : How to stop after finding match whether it's in the first line of text file or the last line ? to simplify stuff if

   if (another_value_to_match == var2)
   values=$(grep -hnr -A2 "$another_value_to_match" exemple.txt | cut -d "=" -f2 | add_something_to_pipe)
   echo $values
   values == X

CodePudding user response:

You are not getting what you think. The instruction

cut -d "=" -f2

is giving you everything after the "=" as a parameter, including the leading space character. You should use

awk -v testor="$another_value_to_match" '{ if( $1 == testor ){ print $3 } }'

or

awk -v testor="$another_value_to_match" '{ if( $1 == testor ){ print $NF } }'

to get a clean return of only the desired string/value, assuming that the value is a single string.

Things get more complicated if the value is multi-string, but I think this will get you thought processes working in the right direction.

CodePudding user response:

How about this:

another_value_to_match="var1"
sed -n "/$another_value_to_match *=/{s:^.*=::;p;q}" example.txt

Explanation:

  • sed -n - run sed with option -n (not auto print)
  • /$another_value_to_match *=/ - find a line containing that text
  • s:^.*=:: - delete everything up to = (inclusive)
  • p;q - print, then quit sed

If you need to get the last value, then run tac to have things in reverse:

tac example.txt | sed -n "/$another_value_to_match *=/{s:^.*=::;p;q}"

(sorry for my broken English)

  • Related