AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 760199
Accepted
Flux
Flux
Asked: 2023-10-30 20:09:20 +0800 CST2023-10-30 20:09:20 +0800 CST 2023-10-30 20:09:20 +0800 CST

Como classificar e filtrar imagens por hora de modificação e visualizá-las no nsxiv no FreeBSD

  • 772

Estou usando o nsxiv para visualizar imagens JPEG e PNG no FreeBSD. No entanto, não consigo encontrar uma maneira de classificar e filtrar as imagens por hora de modificação para visualizá-las no nsxiv no FreeBSD. No Linux com GNU coreutils e GNU findutils, posso usar o comando abaixo para visualizar imagens modificadas após 01/10/2023, classificadas por horário de modificação.

find . -maxdepth 1 -type f \
    \( -iregex '.+\.jpe?g$' -o -iregex '.+\.png$' \) \
    -newermt 2023-10-01 \
    -exec ls -t --zero -- {} + | \
        nsxiv -0 -

Não consigo encontrar um comando equivalente no FreeBSD que seja capaz de lidar com nomes de arquivos que contenham espaços, novas linhas e outros caracteres incomuns. O problema é que o FreeBSD lsnão tem --zeroopção de gerar nomes de arquivos separados por NUL para canalizar para nsxiv. Outro problema é que o FreeBSD findnão possui nenhum arquivo -printf0que possa ser útil para obter tempos de modificação de arquivos que podem ser passados ​​para sort -z. Como classifico e filtro imagens por hora de modificação e as visualizo no nsxiv no FreeBSD?

Estou usando /bin/sh(dash) no Linux e /bin/shno FreeBSD.

shell-script
  • 4 4 respostas
  • 81 Views

4 respostas

  • Voted
  1. Marcus Müller
    2023-10-30T21:14:28+08:002023-10-30T21:14:28+08:00

    Você terá que passar por xargs corretamente para fazer a classificação; então, algo como

    find . -maxdepth 1 -type f \
        \( -iregex '.+\.jpe?g$' -o -iregex '.+\.png$' \) \
        -newermt 2023-10-01 \
        -print0 \
        \|
          xargs -0 \
            stat -n -f '%Y %N\0' \
        \|
          sort -z \
        \|
          cut -z -d ' ' -f2-  \
        \|
          nsxiv -0 -
    

    We use the "decorate – sort – undecorate" trick that you would normally find in languages with tuples. Here, we need to separate our sort key (the time in seconds since epoch, %Y in stat) from our value (the file name) with a space. And then cut that back out. A bit awkward!

    • 2
  2. Claus Andersen
    2023-10-31T09:21:13+08:002023-10-31T09:21:13+08:00

    If it is important for you to be able to make it work on a vanilla FreeBSD system there is another answer with find/xargs/cut/stat. If you are able to install additional utilities there is a cleaner answer using zsh as well.

    But if you are used to GNUism and Linux then it is very easy to live a comfortable life on FreeBSD if you install the GNU findutils.

    pkg install findutils
    

    In the same vein people have got bitten by BSD ls, grep, make, sed and awk. But their GNU counterparts are easily available as well as gnuls, gnugrep, gmake, gsed and gawk. Are you going all in then get coreutils

    They can all coexist with the BSD versions on your system. You will then typically prefix the command with a "g" for the GNU version: gnuls, gfind, gxargs, gmake, gsed and gawk.

    And if you hate to prefix your beloved gnu variants then see "How to make GNU grep the default in FreeBSD?"

    If you get used to the BSD variants instead then they are available on Linux as well. See bsdutils

    • 2
  3. Stéphane Chazelas
    2023-10-31T06:02:52+08:002023-10-31T06:02:52+08:00

    You could do:

    zsh +o caseglob -c '
      autoload after
      print -rN -- *.(jp(e|)g|png)(.e[after 2023-10-01]om)' | nsxiv -0 -
    

    For portability + reliability, perl is likely your best bet:

    perl -MTime::HiRes=lstat -MPOSIX -MFile::Glob=:nocase -e '
      $start = mktime(0,0,0, 1,10-1,2023-1900); # 2023-10-01
      for (<*.{jpg,jpeg,png}>) {
        push @files, [$_, $s[9]] if @s = lstat and -f _ and $s[9] >= $start;
      }
      print "$_->[0]\0" for sort {$b->[1] <=> $a->[1]} @files
      ' | nsxiv -0 -
    

    Note that your -exec ls -t --zero -- {} + won't work properly at sorting the files by modification time if the list of files is big enough that find needs to invoke ls several times.

    • 1
  4. Best Answer
    Flux
    2023-10-31T12:21:39+08:002023-10-31T12:21:39+08:00

    I have found a solution that works in FreeBSD's /bin/sh. I have tried it in FreeBSD 13.2. It seems to properly handle filenames that contain backslashes and whitespace (spaces, tabs, and newlines), including leading and trailing whitespace.

    find . -maxdepth 1 -type f \
            \( -iregex '.\{1,\}\.jpe\{0,1\}g$' -o -iregex '.\{1,\}\.png$' \) \
            -newermt 2023-10-01 \
            -exec ls -l -B -D%s {} + \
        | cut -w -f6- | sort -r | cut -f2- \
        | while IFS="$(printf '\n')" read -r line; do
            printf '%b\0' "$line"
          done \
        | nsxiv -0 -
    

    How it works:

    • ls -l -B -D%s
      • -B displays non-printable characters in octal notation. This is important for handling filenames that contain newlines and tabs.
      • -D%s formats file modification time in seconds since the Epoch. This will be useful for sorting by modification time.
    • cut -w -f6-: remove all columns from the output of ls -l ... except the columns that contain file modification times and filenames. -w is necessary to make consecutive spaces count as one delimiter.
    • sort -r: sort files by modification time from the most recently modified to the oldest.
    • cut -f2-: remove the column of file modification times, leaving only the (newline-separated) filenames.
    • The last part: read the newline-separated filenames one by one and use printf's %b format string to convert the octal notation in the filenames back to the actual characters (i.e. including newline and tabs). Separate the filenames using the NULL character (\0), pipe the NULL-separated filenames into nsxiv -0 -.

    Additional notes:

    • cut -w -f6- | sort -r | cut -f2- cannot be replaced by ls's -t option. As user "Stéphane Chazelas" wrote in another answer on this webpage:

      [find ... -exec ls -t ... -- {} +] won't work properly at sorting the files by modification time if the list of files is big enough that find needs to invoke ls several times.

    • find ... \( -iregex '.\{1,\}\.jpe\{0,1\}g$' -o -iregex '.\{1,\}\.png$' \) could be simplified by using extended regular expressions. e.g. find -E ... -iregex '.+\.(jpe?g|png)$'.
    • In the unusual case where there are space character(s) in the owner or group names, it might be necessary to add the -n option to ls, so that ls outputs user ids and group ids instead of names.
    • 1

relate perguntas

  • Subtraindo a mesma coluna entre duas linhas no awk

  • Um script que imprime as linhas de um arquivo com seu comprimento [fechado]

  • exportar variáveis ​​​​env programaticamente, via stdout do comando [duplicado]

  • Dividir por delimitador e concatenar problema de string

  • MySQL Select com função IN () com array bash

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve