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, 2019 in Linux Administration by Upasana
• 8,620 points
5,922 views

1 answer to this question.

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, 2019 by Shubham
• 13,490 points

Related Questions In Linux Administration

0 votes
1 answer

How to find the first field from a file in Bash Shell?

Hi@akhtar, You can extract text from a file. ...READ MORE

answered Oct 20, 2020 in Linux Administration by MD
• 95,460 points
1,082 views
0 votes
0 answers
–1 vote
1 answer

How to get octal file permission in linux?

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

answered Jan 3, 2019 in Linux Administration by Omkar
• 69,220 points
2,577 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, 2019 in Linux Administration by Omkar
• 69,220 points
1,138 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,240 points
1,185 views
0 votes
1 answer

Script file name in a Bash script

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

answered Jun 20, 2019 in Linux Administration by Shubham
• 13,490 points
770 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, 2019 in Linux Administration by Shubham
• 13,490 points
1,548 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP