Dividir un archivo de nombres en shell

I'm here to know how to split a file name that was found by a ls comand :D. Let me explain better...

Tengo una variable

images=$( ls | grep .img )

And then i want to split the result of the search, because i just want the name before the .img, so a nice idea is use IFS.

IFS=. read -r disk <<< $image

Pretty nice, but when a do an echo with the $disk variable, what i see is a ".img" just that, i want to recover where is before that dot.

Thank you all, and sorry for any mistake :)

preguntado el 10 de septiembre de 13 a las 00:09

Suggestion: add a tag specifying que shell. From the discussion, it's overwhelmingly probably bash, but it's better to be explicit. Even though you've already accepted an answer, it will help future seekers with a similar problem to find that answer. -

3 Respuestas

Use the stream editor sed! Example:

echo "myImage.jpg" | sed 's/.jpg//'

That s means "substitute", and you substitute the part between the first two slashes for the part between the second and third slash, so in the example, ".jpg" for the empty string.

¡Eso es todo!

Respondido el 10 de Septiembre de 13 a las 00:09

thanks, i can't vote to the correctly answer, but you are correct! - Ranu

Since you mention using <<<, I'll assume you are using a shell that supports arrays (specifically, bash. Other shells--notably zsh--may use different syntax for what I am about to describe).

images=( *.img )  # No need to parse ls, which is generally a bad idea

Assuming there is only one matching file, you can then use

disk=${images%.img}

Desnudarse .img from the file name and save the remaining portion in disk. If there could be multiple matches, you can apply the extension stripping to each element of the array and store the result in a second array.

disks=( "${images[@]%.img}" )

Respondido el 10 de Septiembre de 13 a las 00:09

well i coud not understand all, but it helps a lot, and my purpose is just splite the name of the files because i'm using it in a backup! Thanks :D - Ranu

basename es lo que quieres.
Desde la página del manual:

basename - strip directory and suffix from filenames  

    EXAMPLES
           basename /usr/bin/sort
                  Output "sort".
           basename include/stdio.h .h
                  Output "stdio".

Respondido el 10 de Septiembre de 13 a las 00:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.