LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Simple bash/awk/sed scripting question (https://www.linuxquestions.org/questions/programming-9/simple-bash-awk-sed-scripting-question-312407/)

R00ts 04-12-2005 09:34 AM

Simple bash/awk/sed scripting question
 
I'm a little bit confused about the use of awk/sed in a script. I've skimmed through the guides to both and it seems to me like they only operate on files/stdin/stdout, is that right? What I am trying to do is write a simple expression to extract a substring from a bash variable and re-assign the variable to that substring. Specifically the variable consists of an executable's name (+ it's path) and it's inputs. So something like this:


Code:

exec_target="/usr/bin/gcc -c my_program my_program.c"
# And here I want to write an expression to extract "gcc" and reassign it to exec_target


I know there are multiple ways of doing this and I could do it in the blink of an eye if this script I wrote was in Perl, but what's a fast, simple way of doing it in the Bash world and what tool (awk/sed) is best suited for this type of task? Thanks :)

ahh 04-12-2005 09:44 AM

I think this will do what you want, but I may be barking up the wrong tree...
Code:

exec_target=$(echo $exec_target | sed -e 's/.*\///')

R00ts 04-12-2005 10:10 AM

Oh, so sed uses the same matching operator as perl does it? Well that's good to know. :D

Yeah that command yields this:

Code:

exec_target="/usr/bin/gcc -c my_program my_program.c"
exec_target=$(echo $exec_target | sed -e 's/.*\///')
echo $exec_target

> gcc -c my_program my_program.c

So it gets rid of the path, but not the whitespace/other args. I can do that myself though. Thanks!

chrism01 04-15-2005 03:01 AM

exec_target=`echo $exec_target|cut -d' ' -f1`
echo $exec_target
/usr/bin/gcc
exec_target=`basename $exec_target`
echo $exec_target
gcc

dustu76 04-16-2005 02:55 AM

Awk is such a lovely tool ;)

Code:

[/home/soumen/tmp] $ exec_target="/usr/bin/gcc -c my_program my_program.c"
[/home/soumen/tmp] $ exec_target=`echo $exec_target |awk '{print a[split($1,a,"/")]}'`
[/home/soumen/tmp] $ echo $exec_target
gcc

HTH.


All times are GMT -5. The time now is 08:23 PM.