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

Time:02-12

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?

CodePudding user response:

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 =.

CodePudding user response:

Use basename

$file_name=$(basename $entry .txt)
  • Related