Thursday, October 27, 2022

[SOLVED] Once you find match exit in shell script

Issue

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

Solution

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)



Answered By - Bach Lien
Answer Checked By - Marilyn (WPSolving Volunteer)