Extract regexp result from string and write it to variable

I am trying to write a shell script that looks in the file specified as the $ 1 argument for the regular expression and writes the found subpattern to a variable that I can use.

let's say my script is called "dosth.sh" and I have a file "plot.gp" with a line

set output 'test.tex' 

If you now run dosth.sh plot.gp, the script should extract 'test.tex' from plot.gp and write it to a variable.

How is this possible with grep or others?

Thanks and greetings, Jan Oliver

+1
source share
5 answers
 value=`cat $1 | grep -e 'set output' | cut -d'"' -f 2` 

using "instead", and the line above does the job.

+2
source

You can try something in the lines

 value=`grep '^set output' $x | cut -d' ' -f 3` 

(Note that you keep quotes in $value

0
source

dosth.sh:

 #!/bin/bash VALUE=`cat $1 | grep <your regexp here>` echo $VALUE 

it can be used as:

 $ ./dosth.sh a.txt 

then the found lines are stored in the VALUE variable

You can also give regexp for some arguments (given the file name using the script):

dosth.sh:

 #!/bin/bash echo -e "Which file do you want to grep?" read FILENAME args=(" $@ ") VALUE=`cat $FILENAME | grep $args` echo $VALUE 

which can be used as:

 $ ./dosth.sh here comes my * pattern 

Perhaps this link is useful to you: Link

0
source
 variable=$(sed -n '/^set output/ s/[^\x27]*\x27\([^\x27]*\)\x27/\1/p' "$1") 
0
source

value=$( awk -F"'" '$1 == "set output " {print $2}' somefile )

0
source

Source: https://habr.com/ru/post/1435973/


All Articles