Search code examples
bashawkpattern-matchingfilereaderextract-value

Parse specific string my matching pattern from a input text file in bash


I am passing a text file as a command line input to a script and need to parse through the file searching for a specific pattern:

00 TOOL     | Running /variable/directory/path/to/the/tool/executable in batch (pid xxxxx)

Now I have to extract /variable/directory/path/to/the/tool/executable to a variable say $executable.

Here, the portion which remains constant is 00 TOOL | Running at the starting of a line and in batch (pid xxxxx) at the ending of a line where xxxxx is again a variable.

Provided that in the input text file, this line will appear only once.

I have found out the snippet to read line by line, but can not find out a way to read the above said variable:

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
done < "$1"

Any help will be really appreciated!


Solution

  • In case your path's value is not a set field and you want to match it as regex form then try following once.

    val=$(awk 'match($0,/\/[^ ]*/){print substr($0,RSTART,RLENGTH);exit}' Input_file)
    

    You could set its value to a variable by doing var=$(awk code above)