Linux get file without extension

Get just the filename from a path in a Bash script [duplicate]

How would I get just the filename without the extension and no path? The following gives me no extension, but I still have the path attached:

source_file_filename_no_ext=$

6 Answers 6

Many UNIX-like operating systems have a basename executable for a very similar purpose (and dirname for the path):

pax> full_name=/tmp/file.txt pax> base_name=$(basename $) pax> echo $ file.txt 

That unfortunately just gives you the file name, including the extension, so you’d need to find a way to strip that off as well.

So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.

One way to do that (and this is a bash -only solution, needing no other executables):

pax> full_name=/tmp/xx/file.tar.gz pax> xpath=$ pax> xbase=$ pax> xfext=$ pax> xpref=$ pax> echo "path='$', pref='$', ext='$'" path='/tmp/xx', pref='file.tar', ext='gz' 

That little snippet sets xpath (the file path), xpref (the file prefix, what you were specifically asking for) and xfext (the file extension).

I know there is something to do with bash like the above. I just don’t know what the key word is. I would like to get get the pathname, filename, and extension separated into different variables.

If you want to get path use: path=$(echo $filename | sed -e ‘s/\/[^\/]*$/\//’) If you want to get extension: ext=$(echo $filename | sed -e ‘s/[^\.]*\.//’)

@Keith: for pathname, use path=$(dirname $filename) ; there isn’t a command to give you the extension per se, but @paxdiablo showed you how the shell can do it.

@Startec, because that’s how you run an executable (like basname ), capture it’s output, and use that output within a bash command as if you had typed it in explicitly. It’s similar to using backticks but with greater ease of nesting where necessary.

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img" echo "$FILE_PATH" | sed "s/.*\///" 

This returns test.old.img like basename .

This is salt filename without extension:

And following statement gives the full path like dirname command.

It returns /opt/datastores/sda2

this doesn’t work if your path is just file.txt . your second code snipper should be sed -r «s/(.+\/)?(.+)\..+/\2/ instead

I’ve tested @Cardin. seems it works. FILE_PATH=»file.txt»; echo «$FILE_PATH» | sed «s/.*\///»; echo «$FILE_PATH» | sed -r «s/.+\/(.+)\..+/\1/»; echo «$FILE_PATH» | sed -r «s/(.+)\/.+/\1/»; returns 3 times file.txt

Читайте также:  Astra linux microsoft active directory

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev 

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

That’s not a good assumption, and there are tools and commands specificly designed to do this properly.

Additionally, I wouldn’t recommend using the variable name PATH , since this can conflict with the system’s PATH variable

This returns «bad substitution» in bash v4.4.7. I think Fırat KÜÇÜK’s sed solution is better, i.e. $(basename $the_file_path) | sed «s/\..*//»

For me this also gives «bad substitution» error in Bash 4.2.46. But it works if I replace order of operators, i.e. file=$(basename $)

Some more alternative options because regexes (regi ?) are awesome!

Here is a Simple regex to do the job:

Example (grep):

 FP="/hello/world/my/file/path/hello_my_filename.log" echo $FP | grep -oP "$regex" #Or using standard input grep -oP "$regex"  

Example (awk):

 echo $FP | awk 'END #Or using stardard input awk 'END  

If you need a more complicated regex: For example your path is wrapped in a string.

 StrFP="my string is awesome file: /hello/world/my/file/path/hello_my_filename.log sweet path bro." #this regex matches a string not containing / and ends with a period #then at least one word character #so its useful if you have an extension regex="[^/]*\.\w" #usage grep -oP "$regex"  

Total solution with Regexes:

This function can give you the filename with or without extension of a linux filepath even if the filename has multiple "."s in it. It can also handle spaces in the filepath and if the file path is embedded or wrapped in a string.

#you may notice that the sed replace has gotten really crazy looking #I just added all of the allowed characters in a linux file path function Get-FileName()< local FileString="$1" local NoExtension="$2" local FileString=$(echo $FileString | sed 's:\(/[a-zA-Z0-9\\|\\\:\)\(\&\;\,\?\*]*\)\( \)\([a-zA-Z0-9\\|\\\:\)\(\&\;\,\?\*]*/\):\1\3:g') local regex="(? ## call the function with extension Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." ##call function without extension Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." "1" 

If you have to mess with a windows path you can start with this one:

Источник

Read filename without extension in Bash

Linux users need to work with files regularly for many purposes. Sometimes the users need to read the basename of the file only by removing the file extension. Filename and extension can be separated and stored on different variables in Linux by multiple ways. Bash built-in command and shell parameter expansion can be used to remove the extension of the file. How the filename without extension can be read by using the ways mentioned above are explained in this tutorial.

Using `basename` command to read filename

`basename` command is used to read the file name without extension from a directory or file path.

Here, NAME can contain the filename or filename with full path. SUFFIX is optional and it contains the file extension part that the user wants to remove. `basename` command has some options which are described below.

Name Description
-a It is used to pass multiple filenames with path or without path as command arguments.
-s It is used to pass the extension as suffix that needs to remove.
-z It is used to display the multiple filenames by separating each file with null.
–help It is used to display the information of using `basename` command.
–version It is used to display the version information.

Example-1: Using NAME and SUFFIX

The following `basename` command will retrieve the filename with extension. SUFFIX is omitted from this command. Here, the output is ‘product.txt’.

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”. Run the following command to remove the extension from the file.

Example-2: Using ‘-a’ option and NAME

The use of ‘-a’ option of `basename` command is shown in this example. Here, two file paths are passed as arguments with `basename` command. Each filename with extension will retrieve from the path and print by newline.

Example-3: Using ‘-z’ option and NAME

‘-z’ option is used with `basename` command to print the multiple filenames with null value instead of newline. The following command uses two options together, ‘-a’ and ‘-z’. Here, two filenames, index.html and emp.txt will print without any space or newline.

Example-4: Using ‘-s’ option and NAME

The following command can be used as an alternative of SUFFIX with `basename`. File extension needs to pass with ‘-sh’ option to remove the file extension from the file. The following example will remove the extension, ‘-sh’ from the file, ‘addition.sh’.

Example-5: Remove file extension without SUFFIX

If you don’t know the extension of the file that you want to remove from the filename, then this example will help you to solve the problem. Create a file named read_file.sh with the following code to retrieve filename of any extension. `sed` command is used in this example to remove any type of extension from the filename. If you run the script, the output will be ‘average’ after removing the extension ‘py’.

read_file.sh

#!/bin/bash
# Set the filename with path
filename = "/home/fahmida/code/average.py"
# Read the filename without extension by using ‘basname’ and `sed` command
echo " $(basename "$filename" | sed 's/\(.*\) \..*/\1/')"

Example-6: Convert file extension from txt to docx

Filename without extension needs to convert the file from one extension to another. This example shows that how you can change the extension of all text files (.txt) into the word files (.docx) by using `basename` command in the bash script. Create a file named, convert_file.sh with the following code. Here, a for-in loop is used to read all the text files with “.txt” extension from the current directory. The filename without extension is read by `basename` command and renamed by adding “.docx” extension in each iteration of the loop.

convert_file.sh

#!/bin/bash
# the loop will read each text file from the current directory
for filename in ` ls * .txt `
do
# Print the text filename before conversion
echo "Filename before conversion : $filename "
# Change the extension of the file txt to docx
mv -- " $filename " " $(basename -- "$filename" .txt) .docx"
done

Check the text files are converted or not by using `ls` command.

Example-7: Read filename without extension using Shell parameter expansion

Shell parameter expansion is another way to read the filename without extension in bash. This example shows the uses of shell parameter expansion. The following command will store the file pathname in the variable, $filename.

The following command will remove all types of extension from the path and store the file path without extension in the variable, $file1.

The following command will print the filename only from the path. Here, the output will ‘myfile’.

If the filename contains two extensions with two dot(.) and you want to read the filename by removing the last extension of the file then you have to use the following command. Run the following command that store the file path into the variable, $file2 by removing the last extension of the file.

Now, run the following command to print the filename with one dot (.) extension. Here, the output will be “myfile.tar”.

Conclusion

Filename without extension is required for various purposes. Some uses of filename without extension are explained in this tutorial by using some examples such as file conversion. This tutorial will help those users who are interested to learn the ways to separate the file name and extension from the file path. Two ways are explained here. The user can follow any of these ways to extract the filename only from the file path.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector