Unix/ls: Difference between revisions
Content deleted Content added
Corrected tags |
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
||
Line 37:
{{trans|Python}}
<
=={{header|8080 Assembly}}==
Line 44:
filenames in sorted order, so it has to do the sorting itself.
<
puts: equ 9h ; Write string to console
sfirst: equ 11h ; Find first matching file
Line 176:
fcb: db 0,'???????????' ; Accept any file
ds fcb+36-$ ; Pad the FCB out to 36 bytes
fnames:</
=={{header|8th}}==
<
"*" f:glob
' s:cmp a:sort
"\n" a:join .
</syntaxhighlight>
=={{header|Ada}}==
<
procedure Directory_List is
Line 217:
Put_Line(Result.Element(I));
end loop;
end Directory_List;</
=={{header|Aime}}==
<
file f;
text s;
Line 232:
}
r.vcall(o_, 0, "\n");</
=={{header|Arturo}}==
<
=={{header|AWK}}==
{{works with|gawk}} "BEGINFILE" is a gawk-extension
<syntaxhighlight lang="awk">
# syntax: GAWK -f UNIX_LS.AWK * | SORT
BEGINFILE {
Line 249:
exit(0)
}
</syntaxhighlight>
Sample commands and output under Windows 8:
Line 282:
=={{header|BaCon}}==
<
cnt% = 0
files$ = ""
Line 299:
PRINT FLATTEN$(f$)
NEXT
ENDIF</
=={{header|BASIC256}}==
<
#directory$ = dir(currentdir) #Current directory
Line 310:
directory$ = dir()
end while
end</
=={{header|C}}==
C does not have any os-independent way of reading a directory. The following uses readdir and should work on any Unix system.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 379:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.IO;
Line 406:
}
}
}</
=={{header|C++}}==
{{libheader|Boost}}
<
#include <iostream>
#include <set>
Line 428:
std::cout << entry << '\n';
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(doseq [n files] (println (.getName n)))</
=={{header|Common Lisp}}==
Line 441:
The workhorse is `files-list`, which returns a list of filenames. The `ls` function sorts the resulting list and formats it for output.
<
(let* ((dir (concatenate 'string path "/"))
(abs-path (car (directory dir)))
Line 452:
(defun ls (&optional (path "."))
(format t "~{~a~%~}" (sort (files-list path) #'string-lessp)))</
=={{header|D}}==
<
import std.stdio, std.file, std.path, std.array, std.algorithm;
foreach (const string path; dirEntries(getcwd, SpanMode.shallow).array.sort)
path.baseName.writeln;
}</
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
<syntaxhighlight lang="delphi">
program LsCommand;
Line 503:
{$IFNDEF LINUX} readln; {$ENDIF}
end.</
{{out}}
<pre>cd foo
Line 518:
=={{header|EchoLisp}}==
No directory in EchoLisp, which is run in a browser window. Instead, "stores" (folders) and keys in stores (file names) are located in local storage.
<
;; ls of stores (kind of folders)
(for-each writeln (list-sort < (local-stores))) →
Line 535:
Glory
Jonah
</syntaxhighlight>
=={{header|Elixir}}==
<
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(2)> ls.("foo")
Line 548:
a
b
:ok</
=={{header|Erlang}}==
<
1> Ls = fun(Dir) ->
1> {ok, DirContents} = file:list_dir(Dir),
Line 566:
b
[ok,ok,ok,ok]
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<p>Works with .NET framework 4.</p>
<
<p>Prior to .NET4 you had to enumerate files and directories separately.</p>
<p>The call to <code>sort</code> is probably redundant, since "sorted by name" seems to be the default in Windows.</p>
Line 576:
=={{header|Forth}}==
This is much easier without the 'sorted output' requirement:
<
: each-filename { xt -- } \ xt-consuming variant
s" ." open-dir throw { d }
Line 587:
: ]each-filename ]] repeat drop r> close-dir throw [[ ; immediate compile-only
: ls ( -- ) [: cr type ;] each-filename ;</
Given that requirement, we must first generate a sorted array of filenames:
{{libheader|Forth Foundation Library}}
<
dup 1+ allocate throw dup >r place r> ;
Line 606:
: ls ( -- )
[: count cr type ;] each-sorted-filename ;
</syntaxhighlight>
=={{header|Fortran}}==
This is possible only for those Fortran compilers that offer some sort of interface with the operating system's file handling routines. Not standard at all! <
USE DFLIB !Mysterious library.
TYPE(FILE$INFO) INFO !With mysterious content.
Line 626:
END IF !So much for that entry.
IF (MARK.NE.FILE$LAST) GO TO 10 !Lastness is discovered after the last file is fingered.
END !If FILE$LAST is not reached, "system resources may be lost." </
This relies on the supplied routine GETFILEINFOQQ, which is not at all a standard routine, but it does behave in the same way as is found in many other systems, notably with a file name selection filter, here chosen to be "*" meaning "any file". It supplies successive file names and requires mysterious parameters to keep track of what it is doing. In the installation file C:/Compilers/Furrytran/Compaq Furrytran 6.6a CD/X86/DF/INCLUDE/DFLIB.F90, there is the following segment: <
INTEGER*4 FUNCTION GETFILEINFOQQ(FILES, BUFFER,dwHANDLE)
!DEC$ ATTRIBUTES DEFAULT :: GETFILEINFOQQ
Line 642:
INTEGER*4 dwHANDLE
END FUNCTION
END INTERFACE</
Getting this to work was quite annoying. It turned out that the irritating "files" . and .. are deemed a directory (via the bit in INFO.PERMIT matching that of FILE$DIR = 16) and so can be skipped along with proper subdirectories, but the "PERMIT" value of -1 returned for the FILE$LAST state also matches, though its (non-existent) file name length is given as zero. Thus, if one skips directories filter-style by IF ... GO TO 10, in such a case the end will never be seen. Further, although Fortran syntax allows <code>INFO.PERMIT .AND. FILE$DIR</code> the bit values of logical variables are strange. Instead, what is needed is <code>IAND(INFO.PERMIT,FILE$DIR)</code>
Line 651:
=={{header|FreeBASIC}}==
<
Sub ls(Byref filespec As String, Byval attrib As Integer)
Line 663:
Dim As String directory = "" ' Current directory
ls(directory & "*", fbDirectory)
Sleep</
=={{header|Frink}}==
<
println[f.getName[]]</
=={{header|FunL}}==
<
for f <- sort( list(File( "." ).list()).filterNot(s -> s.startsWith(".")) )
println( f )</
{{out}}
Line 700:
The output is indeed sorted, but not all filetypes alltogether: the sorting algorythm is invoked for the different filetypes separately, because it is the way I like it!
<syntaxhighlight lang="furor">
###sysinclude dir.uh
###sysinclude stringextra.uh
Line 781:
{ „temp” }
{ „makestring” #s * dup 10 !+ swap free #g = }
</syntaxhighlight>
{{out}}
Line 856:
=={{header|Gambas}}==
<
Dim sDir As String[] = Dir(User.Home &/ "test").Sort()
Print sDir.Join(gb.NewLine)
End</
Output:
<pre>
Line 872:
=={{header|Go}}==
<
import (
Line 895:
fmt.Println(n)
}
}</
=={{header|Haskell}}==
Line 901:
{{Works with|GHC|7.8.3}}
<
import Data.List
import System.Directory
Line 909:
main = do
files <- getDirectoryContents "."
mapM_ putStrLn $ sort $ filter (dontStartWith '.') files</
=={{header|J}}==
See the [http://www.jsoftware.com/wsvn/base8/trunk/main/main/dir.ijs dir.ijs script] for a full description of the interface for <code>dir</code>:
<
>1 1 dir '' NB. plain filename as per task</
=={{header|Java}}==
{{Works with|Java|11}}
<
package rosetta;
Line 932:
}
}
</syntaxhighlight>
The challenge does not state that the files must be sorted in case-insensitive order, and the majority of solutions in other languages do not bother with same.
The above can be expanded to sort case-insensitively by mapping Path to String and using the predefined String Comparator:
<
Files.list(Path.of("")).map(Path::toString).sorted(String.CASE_INSENSITIVE_ORDER).forEach(System.out::println);
</syntaxhighlight>
=={{header|Javascript}}==
{{Works with|Node.js|4.3.2+}}
<
fs.readdir('.', (err, names) => names.sort().map( name => console.log(name) ));</
=={{header|Jsish}}==
Line 958:
To emulate ''ls'', sorted, one entry per line:
<
=={{header|Julia}}==
<
for e in readdir() # Current directory
Line 969:
# Same for...
readdir("~") # Read home directory
readdir("~/documents")</
=={{header|Kotlin}}==
<
import java.io.File
Line 989:
fun main(args: Array<String>) {
ls(".") // list files in current directory, say
}</
=={{header|Ksh}}==
<
#!/bin/ksh
Line 1,009:
print ${obj}
done
</syntaxhighlight>
=={{header|LiveCode}}==
<
put the folders & the files
set the defaultFolder to "/foo/bar"
put the folders & the files</
=={{header|Lua}}==
Using LuaFileSystem - available in LuaRocks, ULua, major Linux distro repos, etc, etc.
<
for file in lfs.dir(".") do print(file) end</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang
=={{header|Nanoquery}}==
<
import sort
Line 1,033:
for i in range(0, len(fnames) - 1)
println fnames[i]
end</
{{out}}
<pre>.\nanoquery-2.3_1866
Line 1,042:
=={{header|Nim}}==
<
from os import walkPattern
from sequtils import toSeq
for path in toSeq(walkPattern("*")).sorted:
echo path</
=={{header|Objeck}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 1,063:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
Array.iter print_endline (
Sys.readdir Sys.argv.(1) )</
{{Output}}
Line 1,081:
=={{header|PARI/GP}}==
GP doesn't have this capability so we can either use the shell or PARI. For the latter see [[#C|C]]; for the former:
<
in DOS/Windows or
<
in *nix.
Line 1,090:
When tested via Windows XP, the names came out in sorted order (ignoring case) however in earlier systems the files would be presented in entry order. That is, if files a, c, b were saved, they would be named in that order. Then, if file c were deleted and then a file named x were added, they would be named in the order a, x, b. In this case, a scheme for saving an unknown number of names (of unknown length) would be needed so that they could be sorted. Perhaps some linked-list with an insertionsort for each added name...
<syntaxhighlight lang="pascal">
Program ls; {To list the names of all files/directories in the current directory.}
Uses DOS;
Line 1,102:
end;
END.
</syntaxhighlight>
=={{header|Perl}}==
<
while (readdir $handle) {
print "$_\n";
}
closedir $handle;</
Alternatively, using <tt>glob</tt>:
<
<
=={{header|Phix}}==
<!--<
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">})</span>
<!--</
{{Out}}
<pre>
Line 1,137:
=== just names ===
<!--<
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">),</span><span style="color: #004600;">D_NAME</span><span style="color: #0000FF;">)</span>
<!--</
{{Out}}
<pre>
Line 1,148:
===prettier output===
Each element of dir() can be indexed with D_NAME, D_ATTRIBUTES, D_SIZE, D_YEAR, D_MONTH, D_DAY, D_HOUR, D_MINUTE, and D_SECOND, and of course you can easily format these things a bit nicer. Of course there is no way to get a proper directory listing in javascript, so for pwa/p2js we'll just create some fake results.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">dirf</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">date_type</span><span style="color: #0000FF;">=</span><span style="color: #004600;">D_MODIFICATION</span><span style="color: #0000FF;">)</span>
Line 1,176:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
{{out}}
<pre>
Line 1,205:
This will output all the filenames in the current directory.
<
<?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
</syntaxhighlight>
=={{header|Picat}}==
<
main =>
println(ls()),
Line 1,219:
ls() = ls(".").
ls(Path) = [F : F in listdir(Path), F != ".",F != ".."].sort.join('\n').</
=={{header|PicoLisp}}==
<
(prinl F) )</
=={{header|Pike}}==
<
write(file +"\n");</
=={{header|PowerShell}}==
<
Get-ChildItem | Sort-Object Name | Write-Output
# Prints only the name of each file in the directory
Get-ChildItem | Sort-Object Name | ForEach-Object Name | Write-Output</
=={{header|PureBasic}}==
<
If OpenConsole("ls-sim")
Line 1,252:
EndIf
Input()
EndIf</
=={{header|Python}}==
<
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Line 1,270:
pythonw.exe
tcl
>>> </
=={{header|R}}==
<
cat(paste(list.files(), collapse = "\n"), "\n")
cat(paste(list.files("bar"), collapse = "\n"), "\n")
</syntaxhighlight>
{{out}}
<pre>
Line 1,290:
Ooh... warning... if you run the <code>test</code> module (either with DrRacket with the test module automatically running, or with <code>raco test ls.rkt</code>, then the example directory tree is built but not torn down.
<
;; Racket's `directory-list' produces a sorted list of files
Line 1,309:
(parameterize ([current-directory dir]) (with-output-to-string ls)))
(test (ls/str "foo") => "bar\n"
(ls/str "foo/bar") => "1\n2\na\nb\n"))</
Both tests pass.
Line 1,318:
There is a <tt>dir</tt> builtin command which returns a list of IO::Path objects. We stringify them all with a hyperoperator before sorting the strings.
<syntaxhighlight lang="raku"
=={{header|REXX}}==
Line 1,326:
::::* '''b''' is for <u>'''b'''</u>are format (no heading information or summary).
::::* '''o''' is for <u>'''o'''</u>rder, and it orders (sorts alphabetically) by file <u>'''N'''</u>ame.
<
'DIR /b /oN' /*use Windows DIR: sorts & lists.*/
/*stick a fork in it, we're done.*/</
{{out|output|text=''':'''}}
<pre>
Line 1,338:
=={{header|Ruby}}==
<
Dir.foreach("./"){|n| puts n}
</syntaxhighlight>
This will output all files including hidden ones e.g. '.' and '..'.
=={{header|Run BASIC}}==
<
print "rowcount: ";#f ROWCOUNT() ' how many rows in directory
#f DATEFORMAT("mm/dd/yy") 'set format of file date or not
Line 1,356:
print "time: ";#f TIME$() ' time
print "isdir: ";#f ISDIR() ' 1 = is a directory
next</
This will output RunBasics Default Directory.. It can be any directory
<pre>rowcount: 30
Line 1,374:
=={{header|Rust}}==
<
use std::io::{self, Write};
use std::path::Path;
Line 1,397:
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
}</
{{out}}
Line 1,418:
=={{header|S-lang}}==
<
foreach p (array_sort(d))
() = printf("%s\n", d[p] );</
=={{header|Scala}}==
Line 1,452:
=={{header|Seed7}}==
<
include "osfiles.s7i";
Line 1,462:
writeln(name);
end for;
end func;</
=={{header|Sidef}}==
Explicit, by opening the current working directory:
<
Dir.cwd.open.each { |file|
file ~~ < . .. > && next;
Line 1,474:
content.sort.each { |file|
say file;
}</
Implicit, by using the <i>String.glob</i> method:
<
say file;
}</
=={{header|Smalltalk}}==
cheating solution:
{{works with|Smalltalk/X}}
<
real solution:
{{works with|Smalltalk/X}}
<
full 'ls -l' output:
{{works with|Smalltalk/X}}
<
dir directoryContentsAsFilenames sort do:[:fn |
|line|
Line 1,523:
].
line printCR
].</
{{out}}
<pre>-rw-r--r-- xxxxx staff 18436 13 Okt 14:16 .DS_Store
Line 1,533:
=={{header|Standard ML}}==
<
Doing it all by yourself:
<
local (* make a sort function *)
val rec insert = fn s :string =>fn [] => [s]
Line 1,551:
sort result;
</syntaxhighlight>
=={{header|Stata}}==
Stata has a builtin '''[http://www.stata.com/help.cgi?dir dir]''' command (or equivalently '''ls''').
<
6.3k 6/12/17 14:26 auto.dta
2.3k 8/10/17 7:34 titanium.dta
6.0k 8/12/17 9:28 trend.dta</
=={{header|Tcl}}==
<
=={{header|UNIX Shell}}==
ls sorts by default, if it doesn't work for you, pipe it's output to sort :
<
Aamrun $ ls -1
Applications
Line 1,592:
Public
Aamrun $
</syntaxhighlight>
=={{header|Ursa}}==
<
decl string<> fnames
set fnames (sort (f.listdir "."))
Line 1,600:
for (decl int i) (< i (size fnames)) (inc i)
out fnames<i> endl console
end for</
=={{header|Vlang}}==
<
fn main() {
contents := os.ls('.')?
println(contents)
}</
=={{header|Wren}}==
<
var path = "./" // or whatever
// Note that output is automatically sorted using this method.
Directory.list(path).each { |f| System.print(f) }</
=={{header|XPL0}}==
Works on Raspberry Pi.
<
char S;
[S:= "ls";
Line 1,626:
bl system
}
]</
=={{header|zkl}}==
<
Lists all files and directories in the current directory. If you only want a list of files:
<
{{out}}
<pre>
Line 1,639:
The globular method recurses down through the directories. It can send results to objects, functions, methods, threads, etc, etc. To get a sorted list of all the directories under the "Src" directory:
<
{{out}}
<pre>
|