Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get a Substring Using Positive and Negative Indexes in Bash

Tags:

bash

unix

What I want is pretty simple. Given a string 'this is my test string,' I want to return the substring from the 2nd position to the 2nd to last position. Something like: substring 'this is my test string' 1,-1. I know I can get stuff from the beginning of the string using cut, but I'm not sure how I can calculate easily from the end of the string. Help?

like image 403
Eli Avatar asked Sep 08 '11 20:09

Eli


People also ask

How do I get a bash substring after a specified character?

Open the file “input.sh” and write the appended code in the file. Here, we have declared an echo statement with the string “foo-bar-123” using the “awk” keyword. The print term is followed by the “-F-“ keyword. This will create a substring after the next special character, which is “123,” and print it.

How do you fetch particular word in paragraph using shell Linux?

If "name=foo" is always in the same position in the line you could simply use: awk '{print($3)}' , that will extract the third word in your line which is name=foo in your case.


3 Answers

Turns out I can do this with awk pretty easily as follows:

echo 'this is my test string' | awk '{ print substr( $0, 2, length($0)-2 ) }'

like image 173
Eli Avatar answered Nov 15 '22 20:11

Eli


Be cleaner in awk, python, perl, etc. but here's one way to do it:

#!/usr/bin/bash

msg="this is my test string"
start=2
len=$((${#msg} - ${start} - 2))

echo $len

echo ${msg:2:$len}

results in is is my test stri

like image 27
AlG Avatar answered Nov 15 '22 21:11

AlG


You can do this with just pure bash

$ string="i.am.a.stupid.fool.are.you?"
$ echo ${string:  2:$((${#string}-4))}
am.a.stupid.fool.are.yo
like image 27
bash-o-logist Avatar answered Nov 15 '22 20:11

bash-o-logist