Last active
August 29, 2015 14:21
-
-
Save dotSlashLu/c97ec603736a17a2c119 to your computer and use it in GitHub Desktop.
erlang script to find a file in directories using regular expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better be used with shell function to make life a lot more easier