Question

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

I have a 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 :)

Was it helpful?

Solution

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.

That's all!

OTHER TIPS

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}

to strip .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}" )

basename is what you want.
From the man page:

basename - strip directory and suffix from filenames  

    EXAMPLES
           basename /usr/bin/sort
                  Output "sort".
           basename include/stdio.h .h
                  Output "stdio".
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top