1,105,371 Community Members

bash string manipulation

Member Avatar
lewashby
Posting Pro
560 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

echo ${NUM:0:2}

The above is just an example of the kind of code I'M using. I need a way to represent the end of the string. Is there a way to start from the right side of a line of text instead of the left? What I'M trying to do here is grab the last three digits on end, then the next three and so on. NUM in this case will be a user input so there is no way to hard code the end position. Thanks.

Question Self-Answered as of 1 Year Ago
Member Avatar
b1izzard
Junior Poster
118 posts since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
 
0
 

I'm not sure this is what you are asking for but I like to answer part of your question.

Is there a way to start from the right side of a line of text instead of the left? What I'M trying to do here is grab the last three digits on end, then the next three and so on

ravikumar@suselinux:~> echo "123456789" |rev |fold -w 3 |rev
789
456
123
Member Avatar
Watael
Junior Poster
134 posts since Apr 2012
Reputation Points: 4 [?]
Q&As Helped to Solve: 27 [?]
Skill Endorsements: 2 [?]
 
0
 
string=123456789
echo ${string: -3}
789
Member Avatar
cfajohnson
Junior Poster
199 posts since Dec 2008
Reputation Points: 10 [?]
Q&As Helped to Solve: 24 [?]
Skill Endorsements: 0 [?]
 
0
 

No external command is needed:

string=123456789012
while IFS= read -n3 z; [[ $z ]]
do
  echo "$z"
done <<< "$string"
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article