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"

N D Thokare
  • 1,703
  • 6
  • 35
  • 57

2 Answers2

1

Use basename [param] [.ext].

echo `basename $1 .cpp`

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

khachik
  • 28,112
  • 9
  • 59
  • 94
  • 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? – N D Thokare Mar 11 '12 at 03:59
  • @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. – khachik Mar 11 '12 at 10:07
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
amdn
  • 11,314
  • 33
  • 45
  • 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. – N D Thokare Mar 10 '12 at 19:48
  • Ok I fixed it so it would prompt you for input instead of using the arguments to the script – amdn Mar 10 '12 at 21:41