Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[BASH] Possible to echo only certain range of WORDS in a string?

  1. Jun 2, 2012 #1
    Hi,

    I'm new to Bash scripting and I need some help with this:
    I need to echo only a specified range of words from a string based on index;
    so for example if I had:

    a="hello how are you today"

    Is there a way to echo only "how are you" by specifying the index 2 to 4?
    (in one line, possible with one command and without a loop or array?)

    Thanks.
     
  2. jcsd
  3. Jun 2, 2012 #2
    Code (Text):

    echo "hello how are you today" | cut -d' ' -f2-4
     
     
  4. Jun 2, 2012 #3
    Actually I'm not allowed to use cut either haha, but thanks.
     
  5. Jun 3, 2012 #4
    then spell out the complete set of rules...better yet, show what you have tried...you have tried something...haven't you?
     
  6. Jun 3, 2012 #5
    Basically I need to imitate a version of cut without actually using cut.
    Right now I'm passing each line read from file into an array, looping through each element (words, split based on IFS), and then updating an output string each time (I don't want it to print on every new line), then printing the combined output string for that line for each line in the file.

    I was just wondering it there is a shorter way of doing this; ie. I know you can extract certain range of characters from a string with {$var:1:3} or something like that, was just wondering if there is one similar for arrays; I've looked around but couldn't find any.

    Thanks.
     
  7. Jun 3, 2012 #6
    bash does have arrays, though, or lists, if you will
    Code (Text):

    arr=(one two three)
    echo ${arr[1]}
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [BASH] Possible to echo only certain range of WORDS in a string?
Loading...