- Read filename without extension in Bash
- Using `basename` command to read filename
- Example-1: Using NAME and SUFFIX
- Example-2: Using ‘-a’ option and NAME
- Example-3: Using ‘-z’ option and NAME
- Example-4: Using ‘-s’ option and NAME
- Example-5: Remove file extension without SUFFIX
- Example-6: Convert file extension from txt to docx
- Example-7: Read filename without extension using Shell parameter expansion
- Conclusion
- About the author
- Fahmida Yesmin
- Using ‘find’ to return filenames without extension
- 9 Answers 9
- linux find command for filenames without extension for unknown extensions
- 4 Answers 4
- Extract file basename without path and extension in bash [duplicate]
- 9 Answers 9
- ‘ls -1’ : how to list filenames without extension
- 15 Answers 15
- It is not safe to parse ls or to pipe find [1,2]
- Some words more
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.
Источник
Using ‘find’ to return filenames without extension
I have a directory (with subdirectories), of which I want to find all files that have a «.ipynb» extension. But I want the ‘find’ command to just return me these filenames without the extension.
I know the first part:
But how do I then get the names without the «ipynb» extension? Any replies greatly appreciated.
9 Answers 9
To return only filenames without the extension, try:
or (omitting -type f from now on):
however invoking basename on each file can be inefficient, so @CharlesDuffy suggestion is:
Using + means that we’re passing multiple files to each bash instance, so if the whole list fits into a single command line, we call bash only once.
To print full path and filename (without extension) in the same line, try:
To print full path and filename on separate lines:
Here’s a simple solution:
I found this in a bash oneliner that simplifies the process without using find
If you need to have the name with directory but without the extension :
If there’s no occurrence of this «.ipynb» string on any file name other than a suffix, then you can try this simpler way using tr :
The -o flag outputs only the matched part. The -P flag matches according to Perl regular expressions. This is necessary to make the lookahead (?=[.]) work.
Perl One Liner
what you want
find . | perl -a -F/ -lne ‘print $F[-1] if /.*.ipynb/g’
Then not your code
what you do not want
find . | perl -a -F/ -lne ‘print $F[-1] if !/.*.ipynb/g’
NOTE
In Perl you need to put extra . . So your pattern would be .*.ipynb
If you don’t know that the extension is or there are multiple you could use this:
and for a list of files with no duplicates (originally differing in path or extension)
Another easy way which uses basename is:
Using + will reduce the number of invocations of the command (manpage):
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of ‘<>‘ is allowed within the command, and (when find is being invoked from a shell) it should be quoted (for example, ‘<>‘) to protect it from interpretation by shells. The command is executed in the starting directory. If any invocation with the `+’ form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my-command . <> + -quit may not result in my-command actually being run. This variant of -exec always returns true.
Using -s with basename runs accepts multiple filenames and removes a specified suffix (manpage):
support multiple arguments and treat each as a NAME
remove a trailing SUFFIX; implies -a
Источник
linux find command for filenames without extension for unknown extensions
I like using the following command to print file names but it prints them with extensions.
In my directory, there are many files with different extensions. I tried adding —ignore=’*.*’ both before and after -printf , but it didn’t work. example; I have files myfile1.txt, myfile2.mp3, etc. I need it prints myfile1, myfile2, etc. How would I do this?
4 Answers 4
If I understand you correctly (I didn’t, see second part of the answer), you want to avoid listing filenames that contain a dot character.
This will do that:
The filename globbing pattern *.* would match any filename containing at least one dot. The preceding ! negates the sense of the match, which means that the pathnames that gets through to the end will be those of files that have no dots in their names. In really ancient shells, you may want to escape the ! as \! (or update your Unix installation). The lone ! won’t invoke bash ‘s history expansion facility.
To print only the filename component of the found pathname, with GNU find :
With standard find (or GNU find for that matter):
Before using this in a command substitution in a loop, see «Why is looping over find’s output bad practice?».
To list all filenames, and at the same time remove everything after the last dot in the name («remove the extension»), you may use
This would send all found pathnames of all files to a short shell loop. The loop would take each pathname and call basename on it to extract the filename component of the pathname, and then print the resulting string with everything after the last dot removed.
The parameter expansion $
Источник
Extract file basename without path and extension in bash [duplicate]
Given file names like these:
Why this doesn’t work?
What’s the right way to do it?
9 Answers 9
You don’t have to call the external basename command. Instead, you could use the following commands:
Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash , dash , ksh , etc.).
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:
A combination of basename and cut works fine, even in case of double ending like .tar.gz :
Would be interesting if this solution needs less arithmetic power than Bash Parameter Expansion.
Here are oneliners:
I needed this, the same as asked by bongbang and w4etwetewtwet.
Pure bash , no basename , no variable juggling. Set a string and echo :
Note: the bash extglob option must be «on», (Ubuntu sets extglob «on» by default), if it’s not, do:
Источник
‘ls -1’ : how to list filenames without extension
ls -1 lists my elements like so:
I want it listed without the .png like so:
(the dir only contains .png files)
Can somebody tell me how to use grep in this case?
Purpose: I have a text file where all the names are listed without the extension. I want to make a script that compares the text file with the folder to see which file is missing.
15 Answers 15
The sed command removes (that is, it replaces with the empty string) any string .png found at the end of a filename.
The . is escaped as \. so that it is interpreted by sed as a literal . character rather than the regexp . (which means match any character). The $ is the end-of-line anchor, so it doesn’t match .png in the middle of a filename.
You only need the shell for this job.
If you just want to use bash:
You should reach for grep when trying to find matches, not for removing/substituting for that sed is more appropriate:
Once you decide you need to create some subdirectories to bring order in your PNG files you can easily change that to:
I’d go for basename (assuming the GNU implementation):
Another very similar answer (I’m surprised this particular variant hasn’t appeared yet) is:
- You don’t need the -1 option to ls , since ls assumes that if the standard output isn’t a terminal (it’s a pipe, in this case).
- the -n option to sed means ‘don’t print the line by default’
- the /p option at the end of the substitution means ‘. and print this line if a substitution was made’.
The net effect of that is to print out only those lines which end in .png , with the .png removed. That is, this also caters to the slight generalisation of the OP’s question, where the directory doesn’t contain only .png files.
The sed -n technique is often useful in cases where you might otherwise use grep+sed.
You can use only BASH commands to do that (without any external tools).
This is usefully when you’re without /usr/bin and works nice for filenames like this.is.image.png and for all extensions.
wasn’t it enough?
or in general, this
will remove all extensions
It is not safe to parse ls or to pipe find [1,2]
It is not safe to parse (and to pipe) the output of ls or find , mainly because it possible to find in the file names non usual characters as the newline, the tab. Here a pure shell cycle will work [cuonglm] .
Even the find command not piped with the option -exec will work:
Updates/Notes: You can use find . to search even for the hidden files, or find ./*.png to get only the not hidden ones. With find *.png -exec . you can have problem in the case it was present a file named .png because find will get it as an option. You can add -maxdepth 0 to avoid to descend in directories named as Dir_01.png , or find ./*.png -prune -exec . when maxdepth is not allowed (thanks Stéphane). If you want to avoid to list those directories you should add the option -type f (which would also exclude other types of non-regular files). Give it a look to the man for a more complete panorama about all the options available, and remember to check when they are POSIX compliant, for a better portability.
Some words more
It can happen, for example, that copying the title from a document and pasting into the filename, one or more newline will finish in the filename itself. We can be even so unlucky that a title can contain even the key we have to use just before a newline:
If you want to test, you can create file names like this with the commands
The simple /bin/ls *png will output ? instead of the non printable characters
In all the cases in which you will pipe the output of ls or find the following command will have no hint to understand if the present line comes from a new file name or if it follows a newline character in the precedent file name. A nasty name indeed, but still a legal one.
A shell cycle with a shell Parameter-Expansion , $
From the man page of the Shell Parameter Expansion [3]
. the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted.
Источник