How to extract file base name without path and extension in bash?

0 votes

So, I've a few file names like these:

/the/path/foo.txt
bar.txt

I hope to be getting:

foo
bar

I'm trying to do this;

#!/bin/bash

fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname

But it doesn't work. Can anyone help me?

May 31 in Linux Administration by Upasana
• 8,210 points
17 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

You don't actually have to call the external basename command. You could use the following commands,instead:

$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt
$ s=${s##*/}
$ echo ${s%.txt}
foo
$ echo ${s%.*}
foo

Note: This solution worksin all recent (post 2004POSIX compliant shells, (e.g. bash, dash, ksh, etc.).

answered May 31 by Shubham
• 12,890 points

Related Questions In Linux Administration

0 votes
1 answer

How to get octal file permission in linux?

You can use this: stat -c "%a %n" ...READ MORE

answered Jan 3 in Linux Administration by Omkar
• 67,000 points
60 views
0 votes
1 answer

How to take input from user in bash script?

You can use if-else branch to check ...READ MORE

answered Jan 31 in Linux Administration by Omkar
• 67,000 points
21 views
0 votes
1 answer

How to change permissions of folder and files in folder?

The chmod command is used to set/change the permissions ...READ MORE

answered Jan 31 in Linux Administration by Omkar
• 67,000 points
18 views
0 votes
1 answer

how to loop through the content of a file using bash

One of the ways to do it ...READ MORE

answered Feb 15 in Linux Administration by ajs3033
• 7,120 points
52 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How do I set variable if a specific package version is installed in CFEngine?

Here is what you can do.Just use packagesmatching to ...READ MORE

answered Jul 12, 2018 in Other DevOps Questions by Atul
• 10,220 points
63 views
0 votes
1 answer

Script file name in a Bash script

$0 will give you the complete basename. ...READ MORE

answered 6 days ago in Linux Administration by Shubham
• 12,890 points
7 views
0 votes
1 answer

Writing a heredoc to a file in a script

try to use tee: tee newfile <<EOF line 1 line 2 line ...READ MORE

answered May 20 in Linux Administration by Shubham
• 12,890 points
15 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.