1

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 :)

1
  • Suggestion: add a tag specifying which 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.
    – Edward
    Sep 10, 2013 at 1:56

3 Answers 3

1

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!

1
  • 1
    thanks, i can't vote to the correctly answer, but you are correct!
    – ranu
    Sep 9, 2013 at 23:40
1

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}" )
1
  • 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
    Sep 9, 2013 at 23:46
1

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".
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.