1

I'm trying to write a shell script that searches in a file specified as argument $1 for a regex and writes the found subpattern into a variable I can then use.

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

set output 'test.tex'

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

How is that possible with grep or others?

Thanks and regards, Jan Oliver

1
  • unix shell on mac os x. But I figured it out myself. Commented Jul 1, 2010 at 20:10

5 Answers 5

2
value=`cat $1 | grep -e 'set output' | cut -d'"' -f 2`

using " instead of ' and the line above does the job.

Sign up to request clarification or add additional context in comments.

2 Comments

value=cat $1 | grep -e 'set output' | cut -d\" -f 2
-1 This has a number of issues, apart from the formatting problem.
0

You could try something along the lines of

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

(Note that you will retain the quotes in $value

1 Comment

Thanks! Thats nearly what I want, besides those ' in the value.
0

dosth.sh:

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

this can be used as:

$ ./dosth.sh a.txt

then the found strings are stored in the variable VALUE

You can also give the regexp over by some arguments (asked for the filename by 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 like:

$ ./dosth.sh here comes my * pattern

Maybe this link is helpful for you: Link

1 Comment

Thank you for the answer, but the problem is that I want a submatch of the pattern to be stored in my variable, not the hole pattern.
0
variable=$(sed -n '/^set output/ s/[^\x27]*\x27\([^\x27]*\)\x27/\1/p' "$1")

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.