extract regexp result from string and write it to

2020-04-27 03:53发布

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

标签: shell grep
5条回答
叛逆
2楼-- · 2020-04-27 04:23
value=`cat $1 | grep -e 'set output' | cut -d'"' -f 2`

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

查看更多
贪生不怕死
3楼-- · 2020-04-27 04:25

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

查看更多
孤傲高冷的网名
4楼-- · 2020-04-27 04:33

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

查看更多
混吃等死
5楼-- · 2020-04-27 04:35

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

查看更多
我只想做你的唯一
6楼-- · 2020-04-27 04:39
variable=$(sed -n '/^set output/ s/[^\x27]*\x27\([^\x27]*\)\x27/\1/p' "$1")
查看更多
登录 后发表回答