Issue
I have a file having the following structure
destination list
move from station d-435-435 to point place1
move from station d-435-435 to point place2
move from mainpoint
I want to extract the word "d-435-435
"(Only the first match, this need not be same value always) in between the words "from station
" and "to point
"
How can I achieve this?
What I have tried so far?
id=$(sed 's/.*from station \(.*\) to.*/\1/' input.txt)
But this returns the following value: destination list d-435-435 move from mainpoint
Solution
1st solution: With your shown samples, please try following GNU awk
code. Using match
function of awk
program here to match regex rom station\s+\S+\s+to point
to get requested value by OP then removing from station\s+
and \s+to point
from matched value and printing required value.
awk '
match($0,/from station\s+\S+\s+to point/){
val=substr($0,RSTART,RLENGTH)
gsub(/from station\s+|\s+to point/,"",val)
print val
exit
}
' Input_file
2nd solution: Using GNU grep
please try following. Using -oP
option to print matched portion and enabling PCRE regex respectively here. Then in main grep
program matching string from station
followed by space(s) then using \K
option will make sure matched part before \K
is forgotten(since e don't need this in output), Then matching \S+
(non space values) followed by space(s) to point
string(using positive look ahead here to make sure it only checks its present or not but doesn't print that).
grep -oP -m1 'from station\s+\K\S+(?=\s+to point)' Input_file
Answered By - RavinderSingh13 Answer Checked By - Marie Seifert (WPSolving Admin)