fish-shell / fish-shell/fish-shell

Add string find

Open
#5,308 7 comments 1 reaction 0 assignees View on GitHub
RFC
Dominant language
Rust
Stars
34.2k
Forks
2.4k
Avg merge
2d 8h
Merged PRs (30d)
13

Description

I think `find` (or maybe `extract`) would be useful in the `string` commands, to extract text between two search terms.
While grep / sed are common for this, their syntax is often difficult to read and write. Let's suppose it works like this:
```
echo 'a b c d e f' | string find 'b ' -- # returns 'c d e f'
echo 'a b c d e f' | string find 'b ' ' d' -- # returns 'c d'

ip route | string find 'default via ' ' ' # get default gateway
```
A switch could be added, `-t / --terms` to also include the search terms.

It currently can be done with various combinations of `replace`, `split`, `match` and `sub` but usually requires multiple calls, for what seems a very common operation.

Simple implementation:
```
function string_find

cat /dev/stdin | while read -l line

set found (echo $line | string split $argv[1] --)[2]

if test -n "$argv[2]"
set found (echo $found | string split $argv[2] --)[1]
end

echo "$argv[1]$found$argv[2]"
end
end
```

More detailed implementation in fish [here](https://github.com/santpent/fish_funcs/blob/master/fish_funcs.sh) (scroll down to `string_find`).

Compare the equivalent grep and sed syntax:
```
echo "a b c d e" | grep -o -P '(?<=b).*(?=d)'
echo "a b c d e" | sed -e 's/b\(.*\)d/\1/'
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.