unix script using sed

Im trying to get the following script to work, but Im having some issues:

g++ -g -c $1
DWARF=echo $1 | sed -e `s/(^.+)\.cpp$/\1/`

and Im getting -

./dcompile: line 3: test3.cpp: command not found
./dcompile: command substitution: line 3: syntax error near unexpected token `^.+'
./dcompile: command substitution: line 3: `s/(^.+)\.cpp$/\1/'
sed: option requires an argument -- 'e'

and then bunch of stuff on sed usage. What I want to do is pass in a cpp file and then extract the file name without the .cpp and put it into the variable DWARF. I would also like to later use the variable DWARF to do the following -

readelf --debug-dump=info $DWARF+".o" > $DWARF+".txt"

But Im not sure how to actually do on the fly string concats, so please help with both those issues.

Upvotes: 0

Views: 94

Answers (3)

johnnyB
johnnyB

Reputation: 796

In BASH you can crop off the extension from $1 by

${1%*.cpp}

if you need to set the DWARF var use

DWARF="${1%*.cpp}"

or just reference $1 as

readelf --debug-dump=info "${1%*.cpp}.o" > "${1%*.cpp}.txt"

which will chop off the rightmost .cpp so test.cpp.cpp will be test.cpp

Upvotes: 1

SheetJS
SheetJS

Reputation: 22925

You actually need to execute the command:

DWARF=$(echo $1 | sed -e 's/(^.+)\.cpp$/\1/')

The error message is a shell error because your original statement

DWARF=echo $1 | sed -e `s/(^.+)\.cpp$/\1/`

is actually parsed like this

run s/(^.+)\.cpp$/\1/
set DWARF=echo
run the command $1 | ...

So when it says test3.cpp: command not found I assume that you are running with argument test3.cpp and it's literally trying to execute that file

You also need to wrap the sed script in single quotes, not backticks

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77155

You can use awk for this:

$ var="testing.cpp"
$ DWARF=$(awk -F. '{print $1}' <<< $var)
$ echo "$DWARF"
testing

Upvotes: 0

Related Questions