Apr 04, 2008 14:35
Dear Lazywebs:
In Bash, I'm trying to do this:
Given the string "foo bar baz - qux quux.ext" I'd like to come back with two strings: "foo bar baz" and "qux quux".
Really all I need is help figuring out how to count the chars before and after the token.
geekery
Leave a comment
Comments 5
Reply
#!/bin/bash
string1=`echo $1 | cut -d "-" -f 1`
string2=`echo $1 | cut -d "-" -f 2`
string3=`echo $string2 | cut -d "." -f 1`
echo $string1
echo $string3
Now actually getting the length of those strings is a little tougher.
Reply
But won't your code find "-"? Will it work the way I hope if I replace "-" with " - "? (some of the substrings have "-"s in them. The only true delimiter is " - ")
Reply
echo ${#string1}
echo ${#string3}
See this, which probably has a better solution to the whole problem here somewhere, as I note my solution left you with a trailing space on the first string.
Reply
At this point, grep set to return the position of the " - " string inside a string, and cut with the character positions from that might be the way to go.
Or maybe a small C program, using strstr and strncpy would be the way to go.
Or as was mentioned elsewhere, awk, perl, or python.
Reply
Leave a comment