WolframLang Tutorial for Shell Tasks

By Xah Lee. Date: . Last updated: .

The following is a tutorial on WolframLang on shell tasks. Shell tasks are the type of things that Bash or PowerShell do.

Also, these tasks are best done in a text terminal by running it with WolframScript

Navigate Directory

List Files

Get Dir Path, File Name, File Extension, Join Path

Date and Time

Delete Directory

DeleteDirectory returns Null if it succeeds in deleting a directory, and $Failed if it fails.

DeleteDirectory

(* delete a dir only if empty *)
DeleteDirectory["c:/Users/x09908"]
(* delete a dir and all its files and subdirs *)
DeleteDirectory["c:/Users/x09908",DeleteContents->True]

Check is File or Dir

DirectoryQ["c:/Users/xah/abc.txt"]
(* False *)

DirectoryQ["c:/Users/xah/"]
(* True *)
(* is file *)
FileType[ "c:/Users/xah/web/xahlee_info/M/WolframScript.html" ] === File

(* is dir *)
FileType[ "c:/Users/xah/" ] === Directory

(* doesn't exist *)
FileType[ "c:/Users/xah/tt" ] === None

Check File/Dir Existence

(* check file exist *)
FileExistsQ["c:/Users/xah/abc.txt"]
(* True *)

(* works on dir too *)
FileExistsQ["c:/Users/xah/"]
(* True *)

Get File Date

get file date:

FileDate["c:/Users/xah/documents", "Creation"] //DateString
(* Thu 7 Jan 2021 23:27:29 *)

FileDate["c:/Users/xah/documents", "Modification"] //DateString
(* Wed 27 Oct 2021 10:14:25 *)

FileDate["c:/Users/xah/documents", "Access"] //DateString
(* Mon 22 Nov 2021 20:42:58 *)

File Size

get file size:

FileSize["c:/Users/xah/abc.txt"] // Print
(* Quantity[4.681, Kilobytes] *)

Print File Content

print whole file:

FilePrint["c:/Users/xah/abc.txt"]

print just first 9 lines:

FilePrint["c:/Users/xah/abc.txt", 9]

print last 9 lines:

FilePrint["c:/Users/xah/abc.txt", -9]

read/get file content

ReadString["c:/Users/xah/some.html"]

write to file

WriteString[ "c:/Users/xah/some.txt", "something" ]

replace string

StringReplace["some elephant and wolfs", "elephant"->"tiger"]

replace multiple pairs of strings:

(* replace multiple pairs of strings. replacement does not depend on previous replacement. *)

StringReplace["abc", {"a"->"x", "b"->"y", "x"->"H"}]
(* xyc *)

File Hash

FileHash[path]
return integer hash code of file content at path.
FileHash[path, typeStr]
use hash algorithm typeStr. Supported type includes "MD5", "SHA256", "SHA3-256" and more.
FileHash[ "c:/Users/xah/web/xahlee_info/M/WolframScript.html" ]
(* sample return 196936574075229334718916868727866708509 *)

map function to files

FileSystemMap

load WolframScript

load, eval a WolframScript

(*
content of the file is
f =  (x|-> x+1)
*)

(* load the file *)
Get["c:/Users/xah/x1/xx.m"]

Print[f[3]]
(* prints 4 *)

WolframLang: Shell Tasks