Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract file basename without path and extension in bash [duplicate]

Given file names like these:

/the/path/foo.txt bar.txt 

I hope to get:

foo bar 

Why this doesn't work?

#!/bin/bash  fullfile=$1 fname=$(basename $fullfile) fbname=${fname%.*} echo $fbname 

What's the right way to do it?

like image 524
neversaint Avatar asked Apr 19 '10 01:04

neversaint


People also ask

How do I get filenames without an extension in Linux?

If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”.

How do I remove filename extension in bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.

How do you get the name of a file without the extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.


2 Answers

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

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

Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash, dash, ksh, etc.).

Source: Shell Command Language 2.6.2 Parameter Expansion

More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html

like image 129
ghostdog74 Avatar answered Oct 03 '22 05:10

ghostdog74


The basename command has two different invocations; in one, you specify just the path, in which case it gives you the last component, while in the other you also give a suffix that it will remove. So, you can simplify your example code by using the second invocation of basename. Also, be careful to correctly quote things:

 fbname=$(basename "$1" .txt) echo "$fbname" 
like image 42
Michael Aaron Safyan Avatar answered Oct 03 '22 04:10

Michael Aaron Safyan