Skip to content

Instantly share code, notes, and snippets.

@dotSlashLu dotSlashLu/find_in_dir.erl
Last active Aug 29, 2015

Embed
What would you like to do?
erlang script to find a file in directories using regular expression
#!/usr/bin/env escript
%% usage: find_in_dir.erl name dir[ dir2[ ...]]
main(P) ->
[For|L] = P,
{ok, Cwd} = file:get_cwd(),
Matches = flatten(lists:map(fun(Dir) ->
Absdir = case Dir of
"" -> Cwd;
[$/|_] -> Dir;
_ -> Cwd ++ [$/] ++ Dir
end,
{ok, Files} = file:list_dir(Absdir),
Matched = lists:filter(fun(Name) ->
case re:run(Name, For, [caseless]) of
{match, _} -> true;
_ -> false
end
end, Files),
[Absdir ++ [$/] ++ File || File <- Matched]
end,
L)),
case Matches of
[] ->
io:fwrite(standard_error, "No pattern ~p match in ~p~n", [For, L]);
_ ->
MatchedLen = length(Matches),
case MatchedLen of
1 ->
io:format("~s~n", [lists:nth(1, Matches)]);
_ ->
[io:fwrite(standard_error, "~p. ~s~n", [I, lists:nth(I, Matches)]) || I <- lists:seq(1, MatchedLen)],
{ok, [Selected]} = io:fread("", "~d"),
io:format("~s~n", [lists:nth(Selected, Matches)])
end
end.
flatten([]) ->
[];
flatten([H|T]) ->
flatten(T, H).
flatten([H|T], Res) ->
flatten(T, Res ++ H);
flatten([], Res) ->
Res.
@dotSlashLu

This comment has been minimized.

Copy link
Owner Author

commented May 14, 2015

Better be used with shell function to make life a lot more easier

gt() {
  dir=`~/tools/find_in_dirs.erl $1 $PWD ~ ~/projects`
  if [ -d "$dir" ]; then
    cd $dir
  fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.