marlon
marlon

Reputation: 7623

How to parse the file name string from a file path in shell script?

I have files in directory 'new_kb'. I want to iterate on each file and execute a c++ binary on the file, like below:

kb_dir=./new_kb
for entry in "$kb_dir"/*
do
  echo "$entry"
   $file_name  = parse(entry)
  ./build "$file_name"/"$file_name".txt 
  done

One example of 'entry' is:

./new_kb/peopleObj.txt

from the variable path 'entry', I need to parse the string below out:

'peopleObj' 

How to do this in a shell script?

Upvotes: 1

Views: 766

Answers (2)

dan
dan

Reputation: 5211

Using shell built in parameter expansion:

file_name=${entry##*/}
file_name=${file_name%.txt}

Using basename(1):

file_name=$(basename "$entry" .txt)

Note that whitespace is fundamental to how shell commands are parsed, and all variable declarations should have no whitespace around =.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190897

Use basename

$file_name=$(basename $entry .txt)

Upvotes: 0

Related Questions