0

I would like to write a shell script in which I'll take a line input from user,which will contain some xxx.cpp as filename. I want to get that "xxx" in another variable. e.g.

if user give input as:

some params path/to/file/xyz.cpp more p/ara/ms

I want to get xyz which occurs before".cpp" and after last occurance of "/" before ".cpp"

3
  • possible duplicate of Extract filename and extension in bash Commented Mar 10, 2012 at 19:00
  • What if the input is "cp/b.cpp/a.cpp.f.cpp/ foo.cpp cpp/cpp.cpp/b.cpp" You need to clarify what you are asking for. Commented Mar 11, 2012 at 3:37
  • It'll not happen.. user will give only one ***.cpp filename Commented Mar 11, 2012 at 3:55

2 Answers 2

1

Use basename [param] [.ext].

echo `basename $1 .cpp`

where 1 is the index of path/to/file.xyz in the argument list.

Sign up to request clarification or add additional context in comments.

2 Comments

I do not get meaning of "index of"..? if I give the input as: [ some params path/to/file/xyz.cpp more p/ara/ms ] what will be the index and how to get it?
@NDThokare, if it is the complete command-line, where some is the program to run then index of some is 0, index of params is 1 and index of path/to/file/xyz.cpp is 2.
0

Here's a sample bash script to prompt the user for a list of files and filter all the input and display only the base name of files that end in '.cpp' (with .cpp removed) and which are readable

#!/bin/bash
echo Enter list of files:
read list_of_files
for file in $(echo $list_of_files); do
    if echo $file | grep '\.cpp$' > /dev/null; then
        if [[ -r $file ]]; then
            fn=$(basename ${file})
            fn=${fn%.*}
            echo $fn
        fi
    fi
done

2 Comments

if I run this script, its not taking any input at command line. I want to read input from user and use it to extract filename.
Ok I fixed it so it would prompt you for input instead of using the arguments to the script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.