Categorías
hoy aprendí ...

…Windows sigue haciendo de la suyas en la convivencia con Linux, y la partición que te parió!

Otro día en la casa de Gran Hermano, Linux Mint 22 y Windows 10 Home Edition conviviendo bajo una misma CPU, con varias particiones en el medio ¿qué puede salir mal?

Problema: reiniciar en Linux en encontrarse que las particiones NTFS donde antes podía escribir ahora solamente están en modo lectura.

Intento de solución: montaje a mano especificando parámetros. Consultamos unos tutos:
https://forums.linuxmint.com/viewtopic.php?t=231902

https://www.cafecondebian.com/montaje-automatico-de-particiones-con-fstab/

https://proyectopinguino.blogspot.com/2009/04/gestionar-particiones-en-linux-montar-y.html

Y nada!

Pero al intentar hacer el montaje por FSTAB ¡salta la liebre! Un mensaje con un error y posible data.

m@mint22:~$ mount -a
Error opening read-only '/dev/sdc2': Permiso denegado
Failed to mount '/dev/sdc2': Permiso denegado
Please check '/dev/sdc2' and the ntfs-3g binary permissions,
and the mounting user ID. More explanation is provided at
https://github.com/tuxera/ntfs-3g/wiki/NTFS-3G-FAQ
mount: /home/m/media/DATOSO: debe ser superusuario para utilizar mount.
dmesg(1) may have more information after failed mount system call.
mount: (hint) your fstab has been modified, but systemd still uses
the old version; use 'systemctl daemon-reload' to reload.

Vamos a visitar el enlace: https://github.com/tuxera/ntfs-3g/wiki/NTFS-3G-FAQ

WHY DOES NTFS-3G MOUNT MY PARTITION READ-ONLY?

Alternately: Why does ntfs-3g repeatedly want Windows fully shut down?

When Windows 8 (or a subsequent Windows version) is restarted using its fast restarting feature, part of the metadata of all mounted partitions on internal disks is restored to the state it was at the previous closing down. As a consequence, changes made on Linux may be lost. This can happen on any NTFS partition on an internal disk when leaving Windows by selecting «Shut down» or «Sleep». Leaving Windows by selecting «Restart» is apparently safe.

To avoid any loss of data, NTFS-3G forces the read-only mode while mounting.

To get the read-write mode after Windows shut down, make sure the fast restarting of Windows is disabled. This can be achieved by issuing as an administrator the command:

powercfg /h off

En criollo: el Windows, cuando se cierra, deja meadas las particiones «por seguridad» para que otros no las usen.

Categorías
hoy aprendí ...

… a recordar como montar un cdrom en linux

https://linuxconfig.org/how-to-mount-cdrom-in-linux

How to mount cdrom in Linux

15 October 2021 by Luke Reynolds

These days, CDs and DVDs are becoming less popular, in favor of flash drives and other convenient, portable media. However, you still may come across them every once in a while, and if your computer has a CD drive, you should be able to insert a disc and mount it on Linux.

In this tutorial, you’ll see the Linux commands necessary to mount a CDROM.

In this tutorial you will learn:

  • How to mount cdrom in Linux
CategoryRequirements, Conventions or Software Version Used
SystemAny Linux distro
SoftwareN/A
OtherPrivileged access to your Linux system as root or via the sudo command.
Conventions# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Follow along with the steps below to mount a CD or DVD in Linux. Start off by inserting the disc into your computer, then run through these steps:

  1. First, try using the blkid command to see what device file your CD is using. Usually, this is going to be /dev/sr0, but it’s possible that yours is something different. You’ll know it’s the right one because it should say ISO9660Viewing device file path of cdrom in Linux
  2. Next, create a mount point for where you’d like to mount the CD to. Or, just pick an empty directory somewhere on your computer, if you already have a place in mind.$ sudo mkdir /mnt/cdrom
  3. Now we can use the mount command to map the device file to the directory we’ve just created.$ sudo mount /dev/sr0 /mnt/cdrom mount: /mnt/cdrom: WARNING: device write-protected, mounted read-only.
  4. Your CD or DVD should now be accessible in the directory which it was mounted to.$ cd /mnt/cdrom You can also verify that the mount was successful by using the mount command without further options.$ mount | grep cdrom Accessing a mounted cdrom in Linux
  5. When you are done, just unmount the CD and eject it from the disc tray.
    $ sudo umount /mnt/cdrom

Closing Thoughts

In this tutorial, we saw how to mount a CD or DVD rom on Linux systems. As you can see, the process is quite simple, and you will probably be able to do it in the future without a problem, now that you have done it once. Mounting and accessing a CDROM is pretty similar to mounting any other type of media.

Categorías
hoy aprendí ...

… a ordenar archivos en carpetas según el patrón de nombre

Descargando un montón de referencias desde Instagram usando esta maravillosa extensión, Instagram Download Button, me llené de archivos JPG y MP4 y se hacía necesario ordenarlos en carpetas.

El patrón es que todos los archivos tienen en la primer parte del nombre la perfil de Instagram y luego la fecha y hora original del posteo seguidos de un choclazo de números, así que tendría que ser «relativamente» sencillo poder encarpetarlos identificando el perfil.

nombre_perfil-YYYYMMDD_HHMMSS-XXXXXXXXX….. [jpg|mp4]

Buscando en encontré varias propuestas aproximadas para hacer algo como lo que quería

Y la opción ganadora

Extract part of a file name in bash

Específicamente esta respuesta que utiliza el comando SED. La única condición es que la primera parte no sean numeros.

El escenario

I have a folder with lots of files having a pattern, which is some string followed by a date and time:

BOS_CRM_SUS_20130101_10-00-10.csv (3 strings before date)
SEL_DMD_20141224_10-00-11.csv (2 strings before date)
SEL_DMD_SOUS_20141224_10-00-10.csv (3 strings before date)

I want to loop through the folder and extract only the part before the date and output into a file.

Output
BOS_CRM_SUS_
SEL_DMD_
SEL_DMD_SOUS_

La propuesta

Assuming you wont have numbers in the first part, you could use:

$ for i in *csv;do  str=$(echo $i|sed -r 's/[0-9]+.*//'); echo $str; done
BOS_CRM_SUS_
SEL_DMD_
SEL_DMD_SOUS_

Prueba

Cuando hice la prueba, solo mostrando el resultado del SED, funcionaba casi como lo deseaba, con el único tema que era que procesaba algunos archivos con otros patrón de nombre (que no eran necesarios) y los que si debía procesar dejaba el guión del medio.

Ejemplo:

almendromaestro-20220602_195749-285312905_1062446314350240_327302066906487345_n.jpeg

> almendromaestro-

Mi modificación a la RegExp

Agregar un guión que aparece antes de la regla para la fecha, así sólo busca los archivos que se aproximan al patrón.

sed -r 's/-[0-9]+.*//'

y pasó el testeo!

Script terminado

Básicamente hace un loop en todos los archivos que haya en la carpeta, separa el nombre y la almacena en STR (y lo mostramos para ir viendo el progreso), usa eso para verificar que si no existe una carpeta la crea, y luego mueve el archivo a la carpeta.

#!/bin/sh

for i in *.*
do
  str=$(echo $i|sed -r 's/-[0-9]+.*//'); 
  echo $str;
  if [ ! -d $str ]; then
      mkdir $str
  fi
  mv $i $str
done

Y chau!

Categorías
hoy aprendí ...

… a redimensionar varias imágenes con un script bash

Y tenía que procesar varias imágenes escaneadas para bajarles el tamaño de las dimensiones y archivo.

Con ImageMagick en Linux esto se logra con un script bash que recorra los archivos en una carpeta. Me topé con esta solución que me pareció bastante sencilla, hay que hacer algunas cosas previas de manera ‘manual’ pero funciona.

El script trabaja y busca las imágenes sobre una carpeta que se indica dentro del script, con lo que hay que personalizarlo. Tener la precaución de que las imágenes sean copias, porque las reemplaza.

#!/usr/bin/env bash
# Purpose: batch image resizer
# Source: https://guides.wp-bullet.com
# Author: Mike

# absolute path to image folder
FOLDER="/var/www/wp-bullet.com/wp-content/uploads"

# max width
WIDTH=540

# max height
HEIGHT=300

#resize png or jpg to either height or width, keeps proportions using imagemagick
#find ${FOLDER} -iname '*.jpg' -o -iname '*.png' -exec convert \{} -verbose -resize $WIDTHx$HEIGHT\> \{} \;

#resize png to either height or width, keeps proportions using imagemagick
#find ${FOLDER} -iname '*.png' -exec convert \{} -verbose -resize $WIDTHx$HEIGHT\> \{} \;

#resize jpg only to either height or width, keeps proportions using imagemagick
find ${FOLDER} -iname '*.jpg' -exec convert \{} -verbose -resize $WIDTHx$HEIGHT\> \{} \;

# alternative
#mogrify -path ${FOLDER} -resize ${WIDTH}x${HEIGHT}% *.png -verbose

Gracias:

https://guides.wp-bullet.com/batch-resize-images-using-linux-command-line-and-imagemagick/

Y chau.

Categorías
hoy aprendí ...

… y dividir un archivo SQL grande para importarlo

Resulta que tenía que reestablecer la base de datos de un sitio en WordPress dado que una actualización en la base de productos del Woocommerce se había «llenado de basura» y limpiarla era más engorroso que volver a cargar la base (o eso pensaba).

El archivo comprimido del dump sql pesaba 1,5Mb pero un vez expandido eran 18Mb, lo cual generaba que el phpMyAdmin tardara muchísimo en procesarlo y no llegaba a completar la importación.

Entonces se me ocurrió importar el archivo en partes, así que busqué un poco y encontré que con el comando split se puede trocear un archivo de texto plano en varios partes consecutivas.

Gracias a https://unix.stackexchange.com/a/163415

split -l 8000 archivo-de-texto.txt

Esto me genera archivos de 8000 líneas nombrados xaa; xab; xac …

Y chau.