Bash my head in!

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

nolly April 4 2008, 20:12:13 UTC
Seems like a job for awk, maybe? Can't easily provide exact syntax -- I'd just use perl -- but should be well documented.

Reply


whl April 4 2008, 21:07:53 UTC
Note that I do things in a crude fashion:

#!/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

polyfrog April 4 2008, 21:14:28 UTC
I don't actually care about the length. I was going to use some stringy things once I had the positions.

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

whl April 4 2008, 21:16:22 UTC
Ah this gets lengths:
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

whl April 4 2008, 21:19:58 UTC
Yes, I think it would find "-", which I didn't realize was going to be an issue; if you need a multiple character delimiter, then cut is probably not going to do it.

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

Up