Linux if file has extension

How to check the extension of a filename in a bash script?

I am writing a nightly build script in bash.
Everything is fine and dandy except for one little snag:

#!/bin/bash for file in "$PATH_TO_SOMEWHERE"; do if [ -d $file ] then # do something directory-ish else if [ "$file" == "*.txt" ] # this is the snag then # do something txt-ish fi fi done; 

My problem is determining the file extension and then acting accordingly. I know the issue is in the if-statement, testing for a txt file. How can I determine if a file has a .txt suffix?

In addition to the answer of Paul, you can use $(dirname $PATH_TO_SOMEWHERE) and $(basename $PATH_TO_SOMEWHERE) to split into folder and directory and do something directory-ish and file-ish

11 Answers 11

That is, double brackets and no quotes.

The right side of == is a shell pattern. If you need a regular expression, use =~ then.

I didn’t know about this. It seems to be a special case that the right-hand side of == or != is expanded as a shell pattern. Personally I think this is clearer than my answer.

I am new to bash and it took me a little while to figure out how to use this in a multi conditional if statement. I am sharing it here in case it helps someone. if [[ ( $file == *.csv ) || ( $file == *.png ) ]]

@cheflo that’s good for multiple conditions in general. In this specific case, you could also use if [[ $file =~ .*\.(csv|png) ]] . It’s shorter, clearer, easier to add additional extensions and could be easily made configurable (by putting «csv|png» in a variable).

You can put double quotes around the file. if [[ «$file» == *.txt ]] If the file has spaces in its name, double-quoting is required.

@shawnhcorey There is no need for quoting $file, even if it contains a space. The [[ command does not do word splitting (nor pathname expansion). That is one of the main differences between [[ and [, and one of the main reasons to use [[.

I think you want to say «Are the last four characters of $file equal to .txt ?» If so, you can use the following:

Note that the space between file: and -4 is required, as the ‘:-‘ modifier means something different.

In bash, this will produce a «[: ==: unary operator expected» error unless you put quotes around the first variable. So if [ «$» == «.txt» ] instead.

A note for those that may be new to the bash/shell syntax: the space before the -4 is significant. «$» == «.txt» (no space) will not work as expected.

 if [ "$" = "txt" ]; then # operation for txt files here fi 

You just can’t be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use «file». Maybe try using:

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like «text», «application», etc.

Читайте также:  Linux send email to smtp

You can use the «file» command if you actually want to find out information about the file rather than rely on the extensions.

If you feel comfortable with using the extension you can use grep to see if it matches.

yes I am aware of the file command. I had actually tried matching based on the output of said command. but I fail horribly at these if-statements.

The correct answer on how to take the extension available in a filename in linux is:

Example of printing all file extensions in a directory

for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir do echo $ #print extensions done 

Your answer uses a double backslash, but your example only uses a single backslash. Your example is correct, your answer isn’t.

Can you please explain the answer a little bit or link a documentation? I need to understand what does $

Similar to ‘file’, use the slightly simpler ‘mimetype -b’ which will work no matter the file extension.

if [ $(mimetype -b "$MyFile") == "text/plain" ] then echo "this is a text file" fi 

Edit: you may need to install libfile-mimeinfo-perl on your system if mimetype is not available

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I’ve watched online from my firefox cache:

#!/bin/bash # flvcache script CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache OUTPUTDIR=~/Videos/flvs MINFILESIZE=2M for f in `find $CACHE -size +$MINFILESIZE` do a=$(file $f | cut -f2 -d ' ') o=$(basename $f) if [ "$a" = "Macromedia" ] then cp "$f" "$OUTPUTDIR/$o" fi done nautilus "$OUTPUTDIR"& 

It uses similar ideas to those presented here, hope this is helpful to someone.

Источник

Essential Methods to Check if a Linux File has .bash Extension

Learn how to check if a file has the .bash extension in Linux using 5 easy methods. Improve your Bash scripting skills and avoid common issues.

  • Getting the Extension from a Filename in Linux
  • Printing All File Extensions in a Directory
  • Removing the Directory from a Filename
  • Checking if a File Exists in a Bash Script
  • Adding Extensions to Files and Checking for File Extensions in a Directory
  • Other simple code examples for checking the .bash extension of a file
  • Conclusion
  • How to use the if command in Bash?
  • How to check if file exists in Bash?
  • What is the extension for bash script?
  • How to extract a filename and its extension separately in Bash?

As a Linux user, it’s essential to know how to check if a file has the .bash extension. This extension is commonly used in Bash scripts, and having the ability to identify and work with these files can help you become a more efficient and productive Linux user. In this guide, we’ll provide you with several methods to check for the .bash extension in a file, as well as additional tips and best practices for working with Bash scripts.

Getting the Extension from a Filename in Linux

The correct way to get the extension from a filename in Linux is to use the command $ . This command removes all characters from the beginning of the filename up to and including the last dot, leaving only the extension. For example, if you have a file named example.bash , you can use the following command to get the extension:

filename="example.bash" extension=$ echo $extension # Output: bash 

By using this method, you can easily check if a file has the .bash extension by comparing the output of the command to the string “bash”.

Читайте также:  Web мониторинг сервера linux

Printing All File Extensions in a Directory

If you want to print all file extensions in a directory, you can use the following command:

for fname in $(find . -maxdepth 1 -type f); do echo $; done 

This command finds all regular files in the current directory and prints their extensions using the same method as in the previous section. For example, if you have files named example.bash and test.txt in the directory, the output will be:

By using this method, you can easily identify all files with the .bash extension in a directory.

Removing the Directory from a Filename

Sometimes you may want to remove the directory from a filename and return the file name with extension. The basename command can be used to achieve this. For example, if you have a file named /home/user/example.bash , you can use the following command to remove the directory and return the file name with extension:

filename="/home/user/example.bash" basename $filename # Output: example.bash 

By using this method, you can easily obtain a filename with the .bash extension.

Checking if a File Exists in a Bash Script

If you’re working with Bash scripts, you may need to check if a file exists. There are multiple ways to do this, including using conditional expressions or the test command with the -f option. For example, you can use the following code snippet to check if a file exists:

if [ -f "/path/to/file.bash" ]; then echo "File exists" fi 

By using this method, you can easily check if a file with the .bash extension exists in your Bash script.

Adding Extensions to Files and Checking for File Extensions in a Directory

Sometimes you may need to add extensions to files or check for file extensions in a directory. Bash scripts can be used to achieve both of these tasks. For example, you can use the following code snippet to add the .bash extension to all files in a directory:

for file in /path/to/directory/*; do mv "$file" "$.bash" done 

This code snippet uses parameter expansion to remove the extension from the filename and then adds the .bash extension. By using this method, you can easily add the .bash extension to all files in a directory.

You can also use the find command to find all files with the .bash extension in a directory. For example, you can use the following command to find all files with the .bash extension in a directory:

find /path/to/directory -type f -name "*.bash" 

By using this method, you can easily identify all files with the .bash extension in a directory.

Other simple code examples for checking the .bash extension of a file

Conclusion

Checking for the .bash extension in a file is essential for working with Bash scripts in a Linux environment. By using the methods outlined in this guide, you can easily check for the .bash extension, print all file extensions in a directory, remove the directory from a filename, check if a file exists, and add extensions to files or check for file extensions in a directory.

By following these best practices and tips, you can improve your Bash scripting skills and avoid common issues . With these skills, you’ll be able to work more efficiently and productively in a Linux environment.

Источник

Check whether a certain file type/extension exists in directory [duplicate]

Counting lines is parsing. And it will return an incorrect number if any files contain \n (and yes, that is valid in file names).

Pray tell us then, what magical character would have to be in a file’s name in order to make the line count naught?

#/bin/bash myarray=(`find ./ -maxdepth 1 -name "*.py"`) if [ $ -gt 0 ]; then echo true else echo false fi 

+1 for wrapping subshell running find in parenthesis to make myarray an array variable. Otherwise, if find returns no result $ equals 1

Читайте также:  Gparted увеличить раздел linux

This uses ls(1), if no flac files exist, ls reports error and the script exits; othewise the script continues and the files may be be processed

#! /bin/sh ls *.flac >/dev/null || exit ## Do something with flac files here 
shopt -s nullglob if [[ -n $(echo *.flac) ]] # or [ -n "$(echo *.flac)" ] then echo true fi 
#!/bin/bash files=$(ls /home/somedir/*.flac 2> /dev/null | wc -l) if [ "$files" != "0" ] then echo "Some files exists." else echo "No files with that extension." fi 

You need to be carful which flag you throw into your if statement, and how it relates to the outcome you want.

If you want to check for only regular files and not other types of file system entries then you’ll want to change your code skeleton to:

if [ -f file ]; then echo true; fi 

The use of the -f restricts the if to regular files, whereas -e is more expansive and will match all types of filesystem entries. There are of course other options like -d for directories, etc. See http://tldp.org/LDP/abs/html/fto.html for a good listing.

As pointed out by @msw, test (i.e. [ ) will choke if you try and feed it more than one argument. This might happen in your case if the glob for *.flac returned more than one file. In that case try wrapping your if test in a loop like:

for file in ./*.pdf do if [ -f "$" ]; then echo 'true'; break fi done 

This way you break on the first instance of the file extension you want and can keep on going with the rest of the script.

Источник

How to check if a file has an extension (any extension) with regular expression in Bash?

I am new to Bash Scripting using Ubuntu18.04 and trying to find if a file has an extension (any extension) but the regular expression I am trying to implement is not working. I have been using the same regular expression in Perl script and it is working fine. But it does not work in Bash Script.
Below is my Bash Code:

dir="ImageFolder" fileName="" for f in "$dir"/*; do fileName="$(basename "$f")" if [[ $fileName =~ /(.*)?\.(.*)/ ]] then echo $fileName echo "Yes it has extension" fi done 

It does not execute those echo commands even though the files inside “ImageFolder” has their extensions. In other words, the “if” statement is not executing. It only gets executed when I invert the condition by placing a ‘!’ symbol before ‘$fileName’ .
When I invert the condition: if [[ ! $fileName =~ /(.*)?\.(.*)/ ]] then it executes but gives undesired outputs (Please See Image):
It displays files with extension and says yes it has extension

But when I actually remove file extensions by going physically inside the folder then again it executes and says file extension exists (Please see image)
Says ‘Yes It has extensions even though I’ve removed them’

I really need this regular expression to work. Some help will be highly appreciated.

Solution

It should work once you remove the ‘/’ surrounding the regex pattern.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Источник

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