New Reply

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

 
Share Thread Thread Tools
Jun2-12, 06:04 PM   #1
 

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


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.
PhysOrg.com
PhysOrg
science news on PhysOrg.com

>> Bird's playlist could signal mental strengths and weaknesses
>> Minus environment, patterns still emerge: Computational study tracks E. coli cells' regulatory mechanisms
>> Bacterium uses natural 'thermometer' to trigger diarrheal disease, scientists find
Jun2-12, 10:28 PM   #2
 
Code:
echo "hello how are you today" | cut -d' ' -f2-4
Jun2-12, 10:30 PM   #3
 
Actually I'm not allowed to use cut either haha, but thanks.
Jun3-12, 05:42 AM   #4
 

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


then spell out the complete set of rules...better yet, show what you have tried...you have tried something...haven't you?
Jun3-12, 07:19 AM   #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.
Jun3-12, 08:31 AM   #6
 
bash does have arrays, though, or lists, if you will
Code:
arr=(one two three)
echo ${arr[1]}
New Reply
Thread Tools


Similar Threads for: [BASH] Possible to echo only certain range of WORDS in a string?
Thread Forum Replies
Reverse words of a string C++ Engineering, Comp Sci, & Technology Homework 6
Bash range with negative and float numbers Engineering, Comp Sci, & Technology Homework 6
Does string theory predict additional long range forces gravity EM Beyond the Standard Model 1
Range of values of force for string to remain in tension Introductory Physics Homework 11
highest harmonic of a string within typical human's audible range Introductory Physics Homework 2