We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,610 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

bash - trim off the last 4 characters

I'M wanting to write my own command/script for compiling my c++ files. I use g++ -g -Wall filename.cpp -o filename

I'M trying to figure out how I can trip of the last four characters (.cpp) from a string. Any ideas?

5
Contributors
4
Replies
2 Months
Discussion Span
1 Month Ago
Last Updated
13
Views
Question
Answered
Garrett85
Posting Pro in Training
428 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Take a look at the make command, which is made specifically for this kind of thing. Just create a Makefile in the same directory as the source file(s). You can even try this without a Makefile and make MyPrg will compile the file based on the defaults.

#Makefile
MyPrg:
        g++ -O3 -Wall MyPrg.cpp -o MyPrg
        strip MyPrg

debug:  MyPrg.cpp
        g++ -g -Wall MyPrg.cpp -o MyPrg
        touch debug

clean:
        -rm debug MyPrg

To use this Makefile to generate MyPrg, run the make command.
~/src/cpp/MyPrg> make
This will use the first rule to make MyPrg from the given source file. If MyPrg.cpp changes, then calling make will recompile MyPrg.
~/src/cpp/MyPrg> make debug
This will use the debug: rule to create MyPrg to make that version of the program.
~/src/cpp/MyPrg> make clean
This will remove the files generated using this Makefile.

Nutster
Junior Poster
129 posts since Oct 2006
Reputation Points: 62
Solved Threads: 19
Skill Endorsements: 3

I was trying to avoid hard coding MyPrg.cpp and MyPrg. I was going to use ${1} for command line arguments. So I would simply type "compile MyPrg.cpp" and my script would run g++ -g -Wall ${1} -o ${1 - last 4 characters}

Garrett85
Posting Pro in Training
428 posts since Oct 2009
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

hi,

v="myFile.cpp"
((${#v}>4)) && echo "${v:: -4}"

or

v="myFile.cpp"
echo "${v%.cpp}"
Watael
Junior Poster
126 posts since Apr 2012
Reputation Points: 4
Solved Threads: 27
Skill Endorsements: 2
Question Answered as of 4 Months Ago by Nutster and Watael

Also, check out the basename command

rojomoke
Newbie Poster
1 post since Apr 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.0818 seconds using 2.67MB