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?
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.
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.
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 ) }'
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With