0

Let say I have an array $Info whose elements are ;

!    total energy              = -1090.13343774 Ry
!    total energy              = -1090.20757070 Ry
!    total energy              = -1090.24296462 Ry
!    total energy              = -1090.25563488 Ry
!    total energy              = -1090.27085564 Ry
!    total energy              = -1090.27693129 Ry
!    total energy              = -1090.28213580 Ry
!    total energy              = -1090.29131927 Ry

and I want to take its last element , split it with spaces and give to an another array $LastInfo. How can I do that ?

I tried this;

lst=$((${#Info[@]} -1))
IFS=' ' LastInfo=($en[$lst])

But as posted in here the code doesn't work.

  • That is actually still the same problem as your last question. – Julie Pelletier Jun 4 '16 at 5:26
  • 3
    Possible duplicate of What is wrong in this code? – Julie Pelletier Jun 4 '16 at 5:27
  • In last question I asked the mistake in the code but in this one , I am asking how can I do this differently. – onurcanbektas Jun 4 '16 at 5:39
  • 1
    It's the same issue and you're referring to the same code. Your main error is to think that space delimitation wouldn't count the number of spaces in between the columns. – Julie Pelletier Jun 4 '16 at 5:41
  • 1
    Indeed, IFS describes a list of characters to be used as separators, not a string to use. You need a better approach such as column position since your input appears to be fixed. Look at man cut. – Julie Pelletier Jun 4 '16 at 6:04
0
  1. If your array is called Info, and you're calculating the index of the last element of Info, it doesn't make sense to use it to index into en (a different array).
  2. When you do index into an array, you have to use braces;
    not
       $en[$lst]
    but
       ${en[$lst]}
| improve this answer | |
0

What you probably want to do is:

# given that $Info is a populated array..
Lastinfo=(${Info[-1]})

Whitespace is already a default separator, so each space-separated element of the list entry in the Info array will be an entry in the new LastInfo array.

| improve this answer | |
  • Even with this I still taking the first [0] element of $Info – onurcanbektas Jun 4 '16 at 6:05
  • @DopeGhoti: Um, what?  ${#Info[@]} is the number of elements in Info.  And ${Info[-1]} doesn't work in bash. – Scott Jun 4 '16 at 6:10
  • I didn't notice the octothorpe in the ${#Info[@]} construct. And I just tested ${array[-1]} in bash and it worked? See hastebin.com/umedapaqoy.sh – DopeGhoti Jun 4 '16 at 6:15
  • @Scott negative-subscript-from-end is a newish feature; in my 4.3.11+ on Ubuntu /usr/share/doc/bash/NEWS.gz lists it as a change in 4.3 from 4.2. – dave_thompson_085 Jun 4 '16 at 7:57

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.