Jak sprawdzić rozszerzenie nazwy pliku w skrypcie bash?

Piszę nocny skrypt budowania w bashu.
Wszystko jest w porządku i elegancko, z wyjątkiem jednej małej wpadki:


#!/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;
Mój problem polega na ustaleniu rozszerzenia pliku i następnie odpowiednio działającym. Wiem, że problem jest w instrukcji if, testowanie pliku txt.

Jak mogę określić, czy plik ma .przyrostek txt?

Author: Anthon, 2009-01-02

10 answers

Myślę ,że chcesz powiedzieć " czy cztery ostatnie znaki $pliku są równe .txt?"Jeśli tak, możesz użyć następującego:

if [ ${file: -4} == ".txt" ]

Zauważ, że spacja pomiędzy file: i -4 jest wymagana, ponieważ modyfikator': - ' oznacza coś innego.

 171
Author: Paul Stephenson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-11 08:03:33

Make

if [ "$file" == "*.txt" ]

Tak:

if [[ $file == *.txt ]]

Czyli podwójne nawiasy i brak cudzysłowów.

Prawa Strona == to wzór powłoki. Jeśli potrzebujesz wyrażenia regularnego, użyj =~ then.

 194
Author: Georgi K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-09 21:13:35

Możesz użyć polecenia "Plik", jeśli chcesz dowiedzieć się więcej o pliku, a nie polegać na rozszerzeniach.

Jeśli czujesz się komfortowo z używaniem rozszerzenia, możesz użyć grepa, aby sprawdzić, czy pasuje.

 23
Author: Adam Peck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-02 15:54:13

Po prostu nie można być pewnym w systemie Unix, że a .plik txt naprawdę jest plikiem tekstowym. Najlepiej użyć "plik". Może spróbuj użyć:

file -ib "$file"

Następnie możesz użyć listy typów MIME, aby dopasować lub przeanalizować pierwszą część MIME, w której dostajesz takie rzeczy jak "tekst", "aplikacja" itp.

 23
Author: Eldelshell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-02 16:10:01

Można też zrobić:

   if [ "${FILE##*.}" = "txt" ]; then
       # operation for txt files here
   fi
 12
Author: kvz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-03 11:56:45

Podobnie jak 'file', użyj nieco prostszego 'mimetype-b', który będzie działał bez względu na rozszerzenie pliku.

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

Edit: może być konieczne zainstalowanie libfile-mimeinfo-perl w systemie, jeśli mimetype nie jest dostępny

 8
Author: dargaud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 21:44:35

Napisałem skrypt bash, który patrzy na typ pliku, a następnie kopiuje go do lokalizacji, używam go do przeglądania filmów, które oglądałem online z mojej pamięci podręcznej Firefoksa:

#!/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"&

Używa podobnych pomysłów do tych przedstawionych tutaj, mam nadzieję, że jest to pomocne dla kogoś.

 3
Author: desdecode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-01 15:34:33

Myślę, że '$PATH_TO_SOMEWHERE' jest czymś w rodzaju '<directory>/*'.

W tym przypadku zmieniłbym kod na:

find <directory> -maxdepth 1 -type d -exec ... \;
find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;

Jeśli chcesz zrobić coś bardziej skomplikowanego z nazwami katalogów i plików tekstowych, możesz:

find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done

Jeśli masz spacje w nazwach plików, możesz:

find <directory> -maxdepth 1 -type d | xargs ...
find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...
 2
Author: jfg956,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-03 12:18:31

Poprawną odpowiedzią na to, jak pobrać rozszerzenie dostępne w nazwie pliku w Linuksie jest:

${strFileName##*\\.} 

Przykład wydruku wszystkich rozszerzeń plików w katalogu

for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir
    do  echo ${fname##*\.} #print extensions 
done
 2
Author: Albin. Com.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-26 18:05:04

My take on it with cut

>cut -d'.' -f2<<<"hi_mom.txt"
txt

Moje podejście do tego z awk byłoby coś takiego jak poniżej.

>MY_DATA_FILE="my_file.sql"
>FILE_EXT=$(awk -F'.' '{print $NF}' <<< $MY_DATA_FILE)
>if [ "sql" = "$FILE_EXT" ]
>then
>   echo "file is sql"
>fi

>awk -F'.' '{print $NF}' <<eof
>hi_mom.txt
>my_file.jpg
>eof
 1
Author: John Babb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-04 19:29:59