Ben S.
Ben S.

Reputation: 3545

How can I get the contents of a line up to the first occurence of a given string in bash

I'd like all the characters of a line up until the first occurence of a search string.

Examples:

$ echo "onefootwofoothreefoo" | some_command_for_foo
one

 $ echo "123_456_789_" | some_command_for_underscore
123

I've been trying various things with sed and grep but can't get it to work.

Upvotes: 1

Views: 38

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81042

echo "onefootwofoothreefoo" | awk -Ffoo '{print $1}'

echo "123_456_789_" | awk -F_ '{print $1}'

bash only

f=onefootwofoothreefoo
echo "${f%foo${f#*foo}}"

Edit: As pointed out by @JohnB the following also works:

f=onefootwofoothreefoo
echo "${f%%foo*}"

Upvotes: 2

Related Questions