How to find a file extension using UNIX?

I need to find the file extension for the file to be processed using UNIX. The two file extensions that I will process are ".dat" and ".csv".

Please let me know how to do this.

+4
source share
5 answers

So my kick is this.

filename=file.dat extension=$(echo ${filename}|awk -F\. '{print $2}') if [ ${extension} == "dat" ]; then your code here fi 

Cut the $ {filename} pipe variable, which is displayed in awk. With awk reset, field separator on a. then take field 2 (part of $ print)

+2
source
 find . -name "*.dat" -o -name "*.csv" 

Finds in the current directory and recursively down, all files that end in these two extensions.

+18
source

Is this what you want?

 find . -name "*.dat" find . -name "*.csv" 
+3
source

if you have a file name in a variable

 filename = test.csv 

then just use this to get the "csv" part:

 echo ${filename##*.} 

works for bash, try it in ksh

edit:

 filename=test.csv fileext=${filename##*.} if [ fileext = "csv" ]; then echo "file is csv, do something" else if [ fileext = "dat" ]; then echo "file is dat, do something" else echo "mhh what now?" fi fi 
+2
source
 find /path -type f \( -name "*.dat" -o -name "*.csv" \) | while read -r file do echo "Do something with $file" done 
+2
source

Source: https://habr.com/ru/post/1340181/


All Articles