1

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?

2 Answers 2

2

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

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

1 Comment

Worth noting that the parameter expansions are shell built-ins and avoid spawning a subshell that basename (from Linux coreutils) will require. This can provide substantial efficiency benefits if called within a loop (orders or magnitude depending on the number of iterations).
0

Use basename

$file_name=$(basename $entry .txt)

1 Comment

Error: build.sh: line 5: =peopleObject: command not found

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.