Skip to content

Instantly share code, notes, and snippets.

@dotSlashLu
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotSlashLu/c97ec603736a17a2c119 to your computer and use it in GitHub Desktop.
Save dotSlashLu/c97ec603736a17a2c119 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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