Linux get filename without extension

HowTo: Bash Extract Filename And Extension In Unix / Linux

I have setup a shell variable called dest=”/nas100/backups/servers/z/zebra/mysql.tgz”. How do I find out filename (mysql.tgz) and extension (.tgz) in bash program running under Linux or Unix operating systems?

The $ character is used for parameter expansion and command substitution. You can use it for manipulating and/or expanding variables on demands without using

Tutorial details
Difficulty level Easy
Root privileges No/Yes
Requirements Bash
Est. reading time N/A

external commands such as cut, tr, sed or awk.

Find out filename

The syntax is as follows to remove the pattern (front of $VAR):

To get file name, enter:

Find out file extension

The syntax is as follows to remove the pattern from back of $VAR:

Extract filename i.e. filename without extension

The syntax is as follows to remove the pattern from back of $VAR:

To get filename without an extension, enter:

Putting it all together

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Run the script as follows:
backup.bash /backcup/data/server42/latest.tar
Sample outputs:

Again run as follows:
backup.bash /backcup/data/server42/latest.tgz
Sample outputs:

Recommend readings

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

returns to bash, mysql.txz

basename /tmp/other/mysql.txz .txz returns mysql

Leslie, you cannot generalize your scripts. It won’t work if you use anything other than “.txz”.

Источник

Read filename without extension in Bash

Using `basename` command to read filename

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

Syntax:

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.

Options

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

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

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.

Источник

Bash get filename from given path on Linux or Unix

Bash get filename from given path

The basename command strip directory and suffix from filenames. The syntax is pretty simple:
basename /path/to/file
basename /path/to/file suffix

Examples

Let us see how to extract a filename from given file such as /bin/ls. Type the following basename command:
basename /bin/ls
You can pass multiple arguments using the -a option as follows:
basename -a /bin/date /sbin/useradd /nas04/nfs/nixcraft/data.tar.gz
Store outputs in a shell variable, run:

How to remove extesnion from filenames

Remove .gz from backups.tar.gz file and get backups.tar only:
basename /backups/14-nov-2019/backups.tar.gz .gz
OR

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Extract filename and extension in Bash

From the bash man page:

The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. When braces are used, the matching ending brace is the first

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Извлечь имя файла и расширение в Bash

Я хочу, чтобы получить имя файла (без расширения) и расширение отдельно.

лучшее решение я нашел до сих пор:

это неправильно, потому что он не работает, если имя файла содержит несколько . символы. Если, скажем, у меня есть a.b.js , он будет рассматривать a и b.js , вместо a.b и js .

это можно легко сделать в Python с

но я бы предпочел не запускать Python переводчик только для этого, если возможно.

30 ответов

во-первых, получить имя файла без пути:

кроме того, вы можете сосредоточиться на последнем » / «пути вместо». который должен работать даже если у вас есть непредсказуемо расширениями:

дополнительные сведения см. В разделе расширение параметров оболочки в руководстве Bash.

обычно вы уже знаете расширение, поэтому вы можете использовать:

вы можете использовать магию переменных POSIX:

в этом есть оговорка, если ваше имя файла было в форме ./somefile.tar.gz затем echo $ жадно удалил бы самую длинную спичку в . и у вас будет пустая строка.

(вы можете обойти это с помощью временной переменной:

этой сайт больше объясняет.

это не работает, если файл не имеет расширения или имени файла. Вот что я использую; он использует только встроенные имена и обрабатывает больше (но не все) патологические имена файлов.

и вот некоторые тестовые примеры:

вам нужно предоставить basename с расширением, которое должно быть удалено, однако, если вы всегда выполняете tar С -z тогда вы знаете, что расширение будет .tar.gz .

это должно делать то, что вы хотите:

отлично работает, поэтому вы можете просто использовать:

команды, кстати, работают следующим образом.

команда NAME заменяет a «.» символ, за которым следует любое число «.» символы до конца строки, без ничего (т. е. он удаляет все из final «.» до конца строки включительно). Это в основном не жадная подстановка с использованием обмана regex.

команда EXTENSION заменители a любое количество символов, за которыми следует «.» символ в начале строки, без ничего (т. е. он удаляет все от начала строки до конечной точки, включительно). Это жадная подстановка, которая является действием по умолчанию.

Меллен пишет в комментарии к сообщению в блоге:

используя Bash, есть также $ получить имя файла без расширения и $ чтобы получить расширение в одиночку. То есть,

можно использовать cut команда для удаления последних двух расширений ( «.tar.gz» часть):

как отметил Клейтон Хьюз в комментарии, это не будет работать на конкретном примере в вопросе. Поэтому в качестве альтернативы я предлагаю использовать sed с расширенными регулярными выражениями, например:

он работает, удаляя последние два (альфа-числовые) расширения безоговорочно.

[Обновлено снова после комментария от Андерса Линдаля]

нет необходимости беспокоиться с awk или sed или даже perl для этой простой задачи. Есть чистый-Баш, os.path.splitext() -совместимое решение, которое использует только разложений параметра.

Эталонной Реализации

разделить путь пути на пару (root, ext) такое, что root + ext == path и ext пусто или начинается с точки и содержит не более одного периода. Ведущие периоды базовое имя игнорируется; splitext(‘.cshrc’) возвращает (‘.cshrc’, ») .

Реализация Bash

почитание ведущих периодов

игнорирование ведущих периодов

тесты

вот тестовые примеры для игнорирование ведущих периодов реализация, которая должна соответствовать ссылочной реализации Python на каждом входе.

вот некоторые альтернативные предложения (в основном в awk ), включая некоторые расширенные варианты использования, такие как извлечение номеров версий для пакетов программного обеспечения.

все варианты использования, используя исходный полный путь в качестве входных данных, вне зависимости от промежуточных результатов.

[Пересмотрено с однострочного до общего bash функции поведение сейчас соответствует dirname и basename служебные программы; обоснование добавил.]

на принято отвечать работает в типичный делам, а не в edge делам, а именно:

  • для имен файлов без расширения (называется суффикс в остальной части этот ответ), extension=$ возвращает входное имя файла, а не пустая строка.
  • extension=$ не включает начальное . , противоречит Конвенции.
    • слепо знаком . не будет работать для имен без суффикса.
  • filename=»$» будет пустая строка, если имя входного файла начинается с . и не содержит никаких новых . символы (например, .bash_profile ) — противоречит Конвенции.

таким образом, сложность робастное разрешение которое покрывает все случаи края требует функции — см. его определение ниже; это может возвратить все компоненты контура.

обратите внимание, что аргументы после входного пути свободно выбираются, позиционная переменная имена.
Пропустить переменные не из проценты, которые приходят перед теми, которые есть, укажите _ (использовать выбрасываемую переменную $_ ) или » ; например, чтобы извлечь только корень и расширение файла, используйте splitPath ‘/etc/bash.bashrc’ _ _ fnameroot extension .

тестовый код, который выполняет функции:

ожидаемый результат — обратите внимание на граничные случаи:

  • имя файла без суффикса
  • имя файла, начиная с . (не считается началом суффикс)
  • входной путь, заканчивающийся в / (символы / игнорируется)
  • входной путь, который является только имя файла ( . возвращается как родительский путь)
  • имя файла, которое имеет больше, чем . -маркер с префиксом (суффиксом считается только последний):

Источник

Читайте также:  Параллельная работа mac os windows
Оцените статью