How do I change my file extension from me.cpp to me.out or me.cpp to me.exe using Bash scripting.

Thanks!

Recommended Answers

All 10 Replies

filename=me.cpp
# If you use ksh or bash
filename=${filename%cpp}out
# if you use sh
filename=`echo $filename | sed -e s/cpp$/out/`

I want to use either egrep or expr only.

Good for you. Experiment a bit.

I have tried using awk but I still don't see another way of doing the same code but using expr.

Give a better description of what it is you want to do. Have you even tried those things that were posted?

This is what I have from the example:

#!/bin/bash
#
# Replaces blanks with underscores in all the filenames
# of the current directory.

i=0

for filename in *
do
echo "$filename" | grep -q " "
if [ $? -eq 0 ]
then
fname=$filename
n=`echo $fname | sed -e "s/ /_/g"`
mv "$fname" "$n"
((i++1))
fi
done

echo "$i file(s), done."
exit 0

Yes I did use awk. From one of my reference books that don't give solutions, it said to try using expr or egrep for string manipulation.

Well, it's bash, so as I said in my first post

for filename in *.cpp
do
  mv "${filename}" "${filename%cpp}out"
done

However, .cpp to .out usually means you want to compile the files, which has nothing to do with simply renaming them like this.

I understand the last post. However, I want to perform the same code but using expr in the code.

Well that is my question. Why are you fixated on expr? Being so fixated on expr tells me that this is some kind of homework assignment where you expect someone to just give you the answer. Well, the closest I am going to come is to tell you that there is a tutorial at the top of the shell scripting forum, it may, then again it may not, cover expr. Then, there is always google.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.