Chapter 4
In This Chapter
findgrepsedawkChapter 3 got you walking around the filesystem — cd, ls, pwd, say. This chapter teaches you to actually do things to files: make them, copy them, move them, kill them, find them, and look inside them. By the end, you'll have a working file-manipulation toolkit that covers about 95% of what you'll ever need.
A note about scope: cshw has a lot of file commands. We'll spend the most time on the half-dozen you'll use every day, then briskly tour the others so you know they exist for the day you need them. When in doubt, remember that help <command> and man <command> are always available.
To create a folder:
mkdir Projects
mkdir C:\Tools\backup
md scratch
mkdir is the Unix-style name; md is the DOS-style alias. They do the same thing.
If you want to create a folder and any missing parent folders in one shot, use -p ("make parents"):
mkdir -p Projects\cshw\docs\images
That'll create Projects, then Projects\cshw, then Projects\cshw\docs, then Projects\cshw\docs\images, even if none of them existed yet. Without -p, mkdir complains if any intermediate folder is missing.
To remove an empty directory:
rmdir Projects
rd scratch
Same story: rmdir Unix-style, rd DOS-style. With no flags, they only work on empty folders.
To remove a directory and everything inside it, use cshw's /S flag (the same one cmd.exe has used since the dawn of time):
rmdir /S OldProject
rd /S /Q TempFiles
The /S flag means "recurse" — delete every file and subfolder before removing the directory itself. The /Q flag means "quiet" — suppress the per-file error dialogs that would otherwise pop up if something refuses to delete (a locked file, a permission issue). /S /Q together is the standard Windows incantation for "wipe this folder, don't ask me anything."
WARNING
rmdir /S (and its Unix-style equivalent rmdir -r) is the most powerful destructive command in cshw. It recursively deletes everything starting from the path you give it, doesn't prompt, and doesn't stop for read-only files. Like every destructive command in cshw's default mode, it bypasses the Recycle Bin entirely. Always type the path before the flags, then read what you typed before pressing Enter — especially if the path contains environment variables or wildcards like *. For a soft-delete option that handles the whole tree, see /recycle in the next section.
REMEMBER
cshw makes a sharper distinction than bash: rm is for files only, rmdir is for directories only. If you want to wipe a directory tree, that's rmdir /S folder (cmd.exe-style) or rmdir -r folder (Unix-style) — never rm -r. The muscle memory shifts cleanly: when you'd reach for rm -r in bash, type rmdir instead and keep the -r. cshw will tell you rm: 'foldername' is a directory if you forget.
TRY IT
Run mkdir -p test\a\b\c, then cd test\a\b\c, then pwd. You just made four nested folders in one command. Type cd \ to leave, then rmdir /S test to wipe the whole tree in one shot.
cp and copy)cp is the Unix-style copy command; copy is the DOS-style alias. Both do the same thing:
cp report.docx report-backup.docx
cp report.docx C:\Backups\
copy *.txt archive\
Walking through those:
report.docx to a new file called report-backup.docx in the same folder.report.docx into the C:\Backups\ folder, keeping the same filename. (The trailing backslash signals "this is a folder.").txt file from the current folder into the archive\ folder. Globbing happens before cp ever sees the arguments.The flags worth knowing:
cp -r SourceDir DestDir # recursive: copy folder and contents
cp -p file dest # preserve timestamps and attributes
cp -i source dest # interactive: prompt before overwriting
cp -v *.log archive\ # verbose: show what's being copied
TIP
cp will silently overwrite an existing destination file. If you want to be asked first, add -i. If you're moving important files around, the few extra keystrokes are worth it.
REMEMBER
Trailing backslashes matter. cp file folder with no trailing slash creates a file named folder, not a copy into folder. cp file folder\ (with the slash) copies into the existing folder. cshw is usually smart enough to figure out which one you meant, but the slash makes your intent unambiguous.
mv and rename)In Unix, moving and renaming are the same operation: change the file's path. cshw follows that model. mv is the primary name; ren, move and rename all reach it too, so cmd.exe muscle memory works.
mv old-name.txt new-name.txt # rename
mv report.docx C:\Archive\ # move
mv *.log logs\ # move many files
mv is faster than cp followed by rm because, when source and destination are on the same drive, the file isn't actually copied — only its directory entry changes. On the same drive, moving even a 50 GB file is instant. Across drives, it has to copy and then delete.
WARNING
Like cp, mv will overwrite an existing destination file silently. Use mv -i for interactive confirmation, or mv -n ("no clobber") to refuse to overwrite.
rename has a second form for renaming a batch. Give it something to find, something to replace it with, and the files:
rename .txt .bak *.txt # one.txt two.txt -> one.bak two.bak
rename IMG_ photo_ IMG_*.jpg # re-prefix a batch
The two forms are told apart by how many words you give it, and they can't be confused: renaming one file is always exactly two words, and a substitution always needs at least three (a from, a to, and something to apply them to).
If you want a regular expression rather than plain text, that's prename (also installed as file-rename, which is the other name it ships under on Linux):
prename 's/\.jpeg$/.jpg/' *.jpeg
prename 's/(\d{4})-(\d{2})-(\d{2})/$3-$2-$1/' *.txt # reorder a date
prename 'y/A-Z/a-z/' *.TXT # lower-case the names
$1, $2 and so on are the captured groups, exactly as in Perl.
TIP
A bulk rename has no undo. Both commands take -n to change nothing and -v to say what they'd do, so get in the habit of looking first:
prename -n -v 's/^IMG_/photo_/' IMG_*.jpg
REMEMBER
Both of these rewrite the file name only, never the folder path leading to it. rename . _ sub\a.txt renames a.txt inside sub; it will not move the file somewhere else or rename the directory.
rm and del)This is where we slow down, because deletion in cshw is permanent by default. There is no Recycle Bin in the default path. There is no Undo. When you delete a file the normal way, it's gone in the sense that recovering it requires forensic tools.
The basic command:
rm file.txt
del file.txt
rm *.tmp
rm is Unix-style, del is DOS-style — same operation. The third example deletes every .tmp file in the current folder.
The flags you'll meet:
rm -f locked-file.txt # force: skip prompts and ignore read-only
rm -i *.docx # interactive: prompt before each deletion
rm -v *.log # verbose: show what's being deleted
WARNING
rm with a wildcard is dangerous: rm * deletes every file in the current folder, no questions asked, and no Recycle Bin in the default path. The footgun gets worse with environment variables — rm $somevar/*.tmp is dangerous if $somevar is empty (it expands to rm /*.tmp, which deletes any matching files at the root of your drive). Always check what your wildcard expands to before pressing Enter — see the Tip below for a habit that's saved more files than any single Windows feature.
TIP
A safer habit: when you're about to do a destructive rm, run the same pattern through ls first to see exactly what will match. ls *.tmp will show you the files; if the list looks right, recall the command with up-arrow and change ls to rm. This trick has saved more files than any single Windows feature.
/recycle FlagBoth rm and del accept a /recycle (or --recycle) flag that sends the file to the Windows Recycle Bin instead of permanently deleting it:
rm /recycle important-but-i-might-want-it-back.docx
del /recycle *.tmp
rmdir /recycle OldProject
This is the soft-delete safety net that bare Unix shells lack. Files end up in the Recycle Bin where you can right-click → Restore in Explorer, exactly as if you'd hit Delete in the GUI. rmdir /recycle even handles non-empty folders — the entire tree goes to the bin as a single recoverable item, and /S is unnecessary (and silently ignored if you pass it).
REMEMBER
/recycle is strict: if the Recycle Bin can't accept the item (network share, file too big for the bin's per-drive budget, drive without a bin enabled), the command fails rather than silently falling back to permanent delete. PowerShell's Remove-Item -Recycle falls back; cshw refuses. That's a deliberate safety choice — when you ask for recoverable, you get recoverable, or you get an error you can act on.
TIP
A useful habit for new users: alias rm to rm /recycle in your .cshrc for the first few weeks of using cshw, then drop the alias once muscle memory has set in. We'll cover aliases in Chapter 5.
/secure FlagFor sensitive files, rm /secure (or --secure) overwrites the file's contents with zeros before deleting:
rm /secure passwords.txt
This is mutually exclusive with /recycle — you can't both zeroize and recycle. Useful for "make casual recovery harder" cases, but the man page is honest that it's not forensic-grade: journaling filesystems, snapshots, SSD wear-leveling, and OS-level swap files can all leave copies behind. For real anti-forensic work, full-disk encryption is the right tool.
The three deletion modes form a clean hierarchy, from most-recoverable to least:
rm /recycle file # soft delete -- in Recycle Bin, restore anytime
rm file # default permanent delete
rm /secure file # zero-overwrite, then permanent delete
Pick the one that matches your intent. The default sits in the middle by design.
TRY IT
Make a scratch folder with a few junk files, cd into it, run ls, then rm /recycle *, then ls again. The folder is empty. Now open the Recycle Bin in File Explorer — your files are there, ready to be restored.
touch)touch does two related things:
touch newfile.txt
touch -d "2024-01-01" backdated.txt
touch *.log # bump every .log to current time
The first form is the most common — a quick way to create a placeholder file without opening an editor. The second form sets a specific timestamp. The third bumps the modification time of every matching file to right now (useful for forcing a tool to think those files are "fresh").
attrib and chmodWindows files have four classic attributes: Read-only, Archive, System, Hidden. To see and change them, use attrib:
attrib important.docx # show the attributes
attrib +r important.docx # set read-only
attrib -r important.docx # clear read-only
attrib +h secret.txt # hide the file
If you're coming from Unix, the chmod command is also available in cshw — and unlike most Windows shells, it does the real thing. chmod writes actual NTFS ACLs in addition to the legacy read-only attribute, so chmod 644 file.txt produces a file with owner-write / group-and-others-read permissions that NTFS honors. Both numeric (644, 755) and symbolic (u+w, go-r, +x) modes are supported, as is -R for recursive application.
TECHNICAL STUFF
Windows actually has two permission systems: the legacy four-attribute set (R/A/S/H) and the modern ACL system (Access Control Lists, with users, groups, and granular rights). attrib touches only the legacy attributes; chmod touches both — it sets the read-only bit and edits the NTFS ACL so the Unix mode bits are reflected as real Windows permissions. For ACL operations that don't fit Unix mode bits (audit entries, deep ownership transfers, inheritance flags), drop to icacls.
pathmapA small but useful command for cross-platform scripts: pathmap maintains a user-editable table that translates Unix-style paths (/etc/foo, /usr/local/bin) into their Windows equivalents. With a mapping in place, scripts that hard-code Unix paths can be run on Windows without rewriting every literal.
pathmap # list current mappings
pathmap /etc C:\ProgramData # add a mapping
pathmap /home %USERPROFILE%\.. # another
pathmap /etc # show one mapping
pathmap -d /etc # delete
The mapping table is persisted to %APPDATA%\cshw\pathmap.csh, so it survives between sessions (and you can edit or version-control that file directly if you prefer). Reach for pathmap when you're porting a Linux script that's full of /etc/something references and you'd rather keep the script readable than sed every line.
mklinkA link is a filesystem entry that points at another file. There are three flavors:
cshw uses the same mklink syntax Windows itself uses:
mklink hardlink.txt original.txt # hard link to a file
mklink /D linkfolder C:\Some\Real\Folder # symlink to a directory
mklink /H link.txt original.txt # hard link (explicit)
mklink /J junction C:\Real\Folder # junction
Without flags, mklink makes a regular symlink. The flags select the variant.
TIP
Symlinks are great for keeping a single config file in version control while linking to it from wherever the application expects to find it. For example: keep ~/.cshrc in your dotfiles repo, then symlink it into %USERPROFILE%\.cshrc. Edit the repo, the live config updates automatically.
WARNING
Creating symlinks on Windows traditionally required administrator rights. Modern Windows (with Developer Mode enabled) allows non-admin symlink creation, but if mklink fails with "you do not have sufficient privilege," that's why. Either run from sudo or enable Developer Mode in Windows Settings → Update & Security → For Developers.
find, which, where)There are two questions hiding inside "find":
find.foo that the shell would run? — answered by which and where.find — searching the filesystemfind . -name "*.log" # all .log files under current folder
find C:\Projects -name "README*" # all READMEs under Projects
find . -type d -name "test" # directories named "test"
find . -name "*.tmp" -size +1M # tmp files larger than 1 MB
find . -mtime -7 -name "*.log" # logs modified in the last 7 days
The grammar is: find <where> <criteria>. The criteria stack: each one filters further. cshw's find supports the most common Unix-style operators: -name/-iname, -type f|d, -size (with +/- and k/M/G suffixes), -mtime (modification time, in days, again with +/-), -maxdepth, and -mindepth.
TIP
find walks the directory tree, which on a big disk can take a while. If you only want to search the current folder (not subfolders), add -maxdepth 1.
which and where — finding commandsWhen you type git and the shell runs git.exe, where did it find it? which and where answer that question:
which git # show the first git on PATH
where git # show every git on PATH
which cshw # confirm which cshw is being launched
which returns the first match in your PATH (the one that actually runs). where returns every match — useful when you have multiple versions installed and need to know which one wins.
TRY IT
Run where cshw. If you have only one install, you get one path. If you've got cshw installed twice (system and per-user, say), you'll see both — and the first one is the one that runs.
grep)grep searches for text inside files. It is, hands-down, the most useful command in any Unix shell, and cshw's implementation hits all the high notes.
grep "TODO" *.cpp # find TODO in C++ files
grep -i "error" app.log # case-insensitive
grep -n "username" config.cshw # show line numbers
grep -r "password" . # recursive: search subfolders
grep -l "TODO" *.cpp # just filenames, not matches
grep -v "DEBUG" app.log # invert: lines NOT matching
grep -c "ERROR" app.log # count matches
The flags worth memorizing:
-i — case-insensitive-n — show line numbers-r — recurse into subdirectories-l — list filenames only (great for "which files contain X?")-v — invert match-c — count instead of showing matchesgrep also accepts regular expressions, and they're surprisingly powerful:
grep "^Error" log.txt # lines starting with "Error"
grep "[0-9]{3}" log.txt # lines containing a 3-digit number
grep "(WARN|ERROR)" log.txt # WARN or ERROR
Full regex covers an entire chapter on its own; for now, the literal-string search above will handle 90% of what you need.
TECHNICAL STUFF
By default, cshw's grep uses ECMAScript-style regex (via C++'s std::wregex) — the same dialect JavaScript and most modern languages use. For more powerful patterns — lookahead, lookbehind, named groups, Unicode character classes, and JIT-compiled performance on large files — pass the --pcre2 flag. PCRE2 (Perl Compatible Regular Expressions) is the gold standard for regex engines, and cshw includes a JIT-compiled build for speed. The default is plenty for everyday work; reach for --pcre2 when you're doing something elaborate or processing huge files.
TIP
Combine grep with pipes for power. history | grep cd shows every cd you've typed recently. help | grep -i hash finds all the hash-related commands. type log.txt | grep -v DEBUG | wc -l counts the non-debug lines. We'll do much more of this in Chapter 6.
sed)sed (the stream editor) is a Unix tool for editing text as it flows through a pipe. Its most common use is search-and-replace — but unlike a "Find and Replace" dialog in a text editor, sed works on streams, files, and globs of files at once, and you can drive it from a script.
Whole books exist on sed. We'll cover the things you'll actually use day to day; for the rest, man sed is your friend.
The signature sed operation is substitution. Syntax: s/PATTERN/REPLACEMENT/FLAGS.
sed 's/old/new/' file.txt # replace first 'old' on each line
sed 's/old/new/g' file.txt # replace ALL 'old' on each line
sed 's/[Ee]rror/ERROR/g' log.txt # bracket character class
sed -i 's/foo/bar/g' notes.txt # in-place edit (modifies notes.txt)
The default delimiter is /, but you can use any character — handy when your pattern contains slashes (Windows paths, anyone?):
sed 's|C:/old/|D:/new/|g' paths.txt # use | as delimiter
Useful flags inside the substitution: g (replace all on each line, not just the first), i (case-insensitive), p (print only when a substitution was made).
sed does wellsed '/^#/d' config.ini # delete comment lines
sed -n '/ERROR/p' app.log # print only ERROR lines
sed '5,10d' file.txt # delete lines 5 through 10
sed '1,/^$/d' email.txt # delete header up to first blank line
sed -e 's/foo/bar/g' -e '/baz/d' f.txt # multiple commands with -e
The -i flag rewrites the file in place. By default, no backup is kept. Two safer variants:
sed -i.bak 's/old/new/g' file.txt # keep file.txt.bak as backup
sed -i --recycle 's/old/new/g' file.txt # send original to Recycle Bin
TIP
That second variant is a cshw original. sed -i --recycle writes the new content to the file, then sends the original to the Windows Recycle Bin — a soft-delete safety net you don't get on Linux. If your search-and-replace destroys something, you can right-click → Restore from the Recycle Bin and try again. Like rm /recycle, it's strict: if the bin can't accept the file (network share, oversized, etc.), the command fails rather than silently bypassing the safety net.
TECHNICAL STUFF
cshw's sed uses PCRE2 throughout, which is a superset of ERE (extended regex). The classic GNU flags -E / -r (which switch GNU sed from BRE to ERE) are accepted but effectively no-ops — you're already in PCRE2 territory. That means lookahead, lookbehind, named groups, and Unicode classes all work. It also means strict POSIX BRE syntax (where (...) is literal and \(...\) is grouping) is not supported — write modern regex.
TRY IT
Create a small test file: echo "the quick brown fox" > test.txt, then sed 's/quick/slow/' test.txt. The output should read "the slow brown fox" — and test.txt is unchanged because we didn't use -i. Now try sed -i 's/slow/fast/' test.txt, then type test.txt to see the file was rewritten.
sed has hold space, branching, append/insert/change commands, the y/// transliterate operator, file read/write commands, and a fair bit more. cshw implements essentially all of GNU sed plus the --recycle extension. When you reach for something fancier than "search and replace," man sed has the full reference.
awk)awk is a small programming language whose entire purpose is processing text organized into records (lines) and fields (columns). Think of it as "a tiny spreadsheet engine you drive from a pipe." Like sed, whole books exist on awk. We'll teach you enough to do real work; the rest is in man awk.
The signature awk operation is column extraction:
awk '{ print $2 }' file.txt
That prints the second whitespace-separated field of every line. $1 is the first field, $2 the second, $NF the last (NF = "number of fields"), $0 the whole line.
The -F flag sets the field separator:
awk -F, '{ print $1 }' data.csv # first column of CSV
awk -F: '{ print $1 }' /etc/passwd-like.txt # colon-separated
awk -F'|' '{ print $1, $3 }' piped.txt # pipe-separated
Multi-character delimiters work too — awk -F'||' '{ print $2 }' splits on ||.
An awk program is a sequence of pattern { action } rules. A pattern decides which lines an action applies to:
awk '/ERROR/ { print NR, $0 }' log.txt # line number + content of ERROR lines
awk 'NR == 1 { next } { print }' csv.txt # skip the header row
awk 'length($0) > 80' data.txt # bare pattern: prints lines > 80 chars
awk '$3 > 100 { print $1 }' data.txt # filter by numeric field, project
The two special patterns BEGIN and END run once before any input and once after all input — perfect for initialization and aggregation:
awk 'BEGIN { sum = 0 } { sum += $1 } END { print sum }' nums.txt
That sums the first column. BEGIN initializes the running total, the bare action accumulates, END prints the result.
awk arrays are indexed by strings, not numbers. That makes them perfect for counting, grouping, and lookups:
awk '{ count[$1]++ } END { for (k in count) print k, count[k] }' words.txt
That builds a frequency table of the first column — count[k] holds how many times each unique value appeared. The END { for (k in count) ... } walks the array and prints each key with its count.
Combined with sort, this becomes one of the most useful idioms in any shell:
type access.log | awk '{ ip[$1]++ } END { for (i in ip) print ip[i], i }' | sort -rn
That counts unique IP addresses in a web log and sorts them by frequency, descending. Five tools, one pipeline, no programming language required.
NR — current record number (line count so far)NF — number of fields on the current lineFS — field separator (input)OFS — field separator (output, used by print)FILENAME — name of the current input file$0, $1, $2, $NF — fields, as already shownThe most-used ones: length(s), substr(s, start, len), index(haystack, needle), split(s, arr, sep), sub(re, repl) and gsub(re, repl) (substitute first / all matches in $0), tolower(s), toupper(s), sprintf(fmt, ...), int(x), plus the math standards (sqrt, exp, log, sin, cos).
TIP
Use -v VAR=VALUE to pass values from the shell into your awk program: awk -v threshold=100 '$1 > threshold' nums.txt. That's much cleaner than embedding shell variables in the awk program (which is an escaping nightmare).
Once a program grows past a couple of rules, you want to name things:
function fahrenheit(c) { return c * 9 / 5 + 32 }
{ print $1, fahrenheit($2) }
Definitions sit at the top level alongside the rules, and you can call a function from a line above the one that defines it — which matters, because mutually recursive helpers have no other option.
awk has no local keyword. Instead, extra parameters are the locals: you call with fewer arguments than the function names, and the rest arrive uninitialized. The convention is to leave a wide gap before them, which tells the reader what is going on and means nothing at all to the parser:
function total(arr, k, sum) { # arr is the argument; k and sum are locals
for (k in arr) sum += arr[k]
return sum
}
One rule repays learning early: scalars are copied, arrays are shared. You do not choose this at the call site — it follows from what the variable already holds.
function bump(n, A) { n = 99; A["k"] = "set" }
BEGIN { x = 1; bump(x, arr); print x, arr["k"] } # prints: 1 set
x is untouched because numbers pass by value; arr gains an element because arrays pass by reference. That is what lets a function fill an array for its caller, which is how split() has always worked.
⚠️ A call needs the parenthesis hard against the name. With a space,
f (x)is concatenation of a variable and a parenthesized expression — which is exactly what the standard string-building idiom relies on:s = s (k > 1 ? "," : "") A[k]. Built-in names are the documented exception, solength (x)is still a call.
system()awk '{ system("touch " $1) }' names.txt
system() runs a command, waits for it, and hands back its exit status. It is the same call C programmers have used since Turbo C days, and awk inherited it from there.
In cshw the command goes through cshw itself by default, which is the compatible choice rather than the parochial one: awk programs in the wild are written against a Unix shell and call things like system("rm -f " tmp). cshw has rm; cmd.exe does not. A script ported from Unix therefore stands a chance of running unchanged.
When you want a different shell, name it as a first argument. The names are case-insensitive and each shell answers to several spellings:
| you write | you get |
|---|---|
system("ls -l") |
cshw — the default |
system("cmd", "dir /w") |
cmd.exe /c |
system("ps", "Get-Process") |
PowerShell |
system("bash", "ls | wc -l") |
bash, if it is installed |
bash is allowed to fail rather than quietly fall back to another shell — running bash syntax under cmd.exe would not report an error, it would run something else entirely.
close()awk keeps a file or command open once you have used it, which is usually what you want and occasionally exactly what you don't:
BEGIN {
print "data" > "out.txt"
close("out.txt") # flush it, so it can be read back
while ((getline line < "out.txt") > 0) print line
}
The other use is re-running a command. A second "date" | getline sits at the end of the first run's output and returns 0 forever; close("date") makes the next one start over.
ARGV and ARGC hold the operands, ENVIRON holds the environment:
awk 'BEGIN { for (i = 1; i < ARGC; i++) print "input:", ARGV[i] }' a.txt b.txt
awk 'BEGIN { print ENVIRON["USERNAME"] }'
ARGV[0] is "awk", and ARGV[1..] are the operands in the order you gave them — file names and var=value assignments alike.
next abandons the current record. nextfile abandons the whole rest of the current input file and moves to the next one — handy when the first line tells you the file is not one you care about:
awk 'FNR == 1 && $0 !~ /^#version 2/ { nextfile } { print FILENAME": "$0 }' *.cfg
awk has one numeric type: the double. An integral value always prints as an integer, however large:
awk 'BEGIN { print 1e17 }' # 100000000000000000, not 1e+17
Non-integral values go through OFMT for print and CONVFMT everywhere else — concatenation, array subscripts, comparisons. Both default to %.6g, which is six significant digits:
awk 'BEGIN { print 1/3 }' # 0.333333
awk 'BEGIN { OFMT="%.10f"; print 1/3 }' # 0.3333333333
That %.6g default is the reason a long decimal sometimes looks rounded when you print it and exact when you compare it. The value never changed; only its rendering did.
TECHNICAL STUFF
cshw's awk uses PCRE2 as its regex engine, just like sed and (with --pcre2) grep. So /[Ee]rror/ works, but so do PCRE2-only features like lookahead and named groups. Output redirection is fully wired: print and printf to > file, >> file, and | command all do what you'd expect. User-defined functions, getline in all four forms, close(), system(), ARGC/ARGV/ENVIRON, CONVFMT/OFMT, nextfile, and regex separators for split() all work. The remaining gaps are narrow: no BEGINFILE/ENDFILE, and a plain getline stops at the end of the current file rather than rolling into the next. man awk lists them, along with the handful of places cshw deliberately follows POSIX where gawk does not.
TRY IT
Save this as data.txt:
alice 30
bob 25
carol 40
dave 35
Then run awk '{ sum += $2 } END { print "average:", sum/NR }' data.txt. You should see average: 32.5. That's a four-line program in any other language, condensed to one shell pipeline.
awk's grammar is bigger than what we've shown — it supports proper if/else, while/for loops, break/continue/next/exit, ternary expressions, regex match operators (~ and !~), and a full set of string and numeric operators. For all of that, man awk has the full reference, with examples for the patterns you're most likely to need.
When you don't know what a file is, cshw has several commands for peeking at it.
file — identifies file type by magic bytes (the first few bytes of the file), much more reliable than trusting the extension:
file report.docx # Microsoft Word document
file mystery.dat # PNG image, 800x600, 8-bit
file install.exe # PE32+ executable (Windows)
stat — full filesystem info: size, timestamps, permissions, attributes:
stat report.docx
hexdump — show the file in hexadecimal, byte by byte. Useful for inspecting binary file headers, debugging encoding issues, or just satisfying curiosity:
hexdump -n 64 image.png # first 64 bytes
hexdump -C report.docx # canonical hex+ASCII format
strings — extract printable text from a binary. Often surprisingly informative:
strings program.exe | grep -i version
peinfo — Windows-specific. Shows information about Portable Executable files (.exe, .dll): linked DLLs, exported functions, embedded resources, etc.:
peinfo notepad.exe
peinfo myplugin.dll
TECHNICAL STUFF
peinfo is genuinely useful for plugin development. When you build a cshw plugin DLL (Chapter 18), peinfo myplugin.dll will show you whether RegisterCommandLibrary is exported correctly. It's the fastest sanity check before trying to load the plugin into the shell.
wc — word count, but it counts lines, words, and bytes:
wc report.txt # lines words bytes
wc -l *.cshw # just line counts
wc -w report.txt # just word count
lc (also linecount) — a line-count shortcut with pattern matching:
lc *.cpp # lines per .cpp file, with totals
diff — compare two text files line by line:
diff old.txt new.txt
diff -u old.txt new.txt # "unified" format (the kind git uses)
If two files are identical, diff says nothing. If they differ, you get a report of the changes. Combine with -r to compare entire directories.
tarcshw includes a real tar for creating, extracting, and listing tar archives — including the gzipped variants (.tar.gz, .tgz):
tar -czf project.tar.gz Projects\cshw\ # create gzipped archive
tar -xzf project.tar.gz # extract
tar -tf project.tar.gz # list contents (don't extract)
tar -xzf project.tar.gz -C C:\Restore\ # extract to specific folder
The flags read like a sentence. c create, x extract, t list. z gzip. f filename (always followed by the archive name). v verbose if you want to see each file as it's processed. So czvf is "create, gzipped, verbose, filename follows."
TIP
Windows users sometimes get tripped up by tar because it's been a Unix staple for fifty years and has opinions. The big one: tar archives are typically structured around a top-level folder. When you create one with tar -czf foo.tar.gz Projects\cshw\, the archive contains a Projects\cshw\ folder. Extracting it elsewhere recreates that structure. If you want a flat archive, cd into the source folder first and use tar -czf ../foo.tar.gz ..
zipFor Windows-native archives, cshw also includes a real zip command — useful when you're sharing files with someone who lives in Explorer and would prefer not to install 7-Zip just to open your archive:
zip backup.zip report.docx # archive a single file
zip /r project.zip C:\Projects\cshw\ # archive a folder recursively
zip /p secrets.zip private.txt # encrypt with prompted password
zip /p:hunter2 secrets.zip private.txt # encrypt with literal password
The flags:
/r — recurse into subdirectories/p — encrypt entries with AES-256. Plain /p prompts you for a password (with confirmation); /p:value takes the password literally as part of the command line.WARNING
/p:hunter2 puts the password in your shell history (where you can recall it with up-arrow forever) and in any logs that capture your command line. For anything sensitive, use bare /p and let cshw prompt you.
TECHNICAL STUFF
cshw's zip produces archives that are interoperable with the Windows-style "compressed folder" extension, 7-Zip, WinRAR, the Java jar tool, and the Python zipfile module. It does not preserve POSIX permissions or symbolic links, and it stores timestamps at 2-second resolution (the DOS-time legacy). For Unix-flavored interchange, use tar.
When you download something from the internet, the publisher often provides a hash — a long hex string — so you can verify the file wasn't tampered with or corrupted in transit. cshw has the standard hash commands:
md5sum installer.exe
sha1sum installer.exe
sha256sum installer.exe
sha512sum installer.exe
shasum -a 256 installer.exe # specify bit size to shasum
To verify, compare the output to the expected hash from the website:
sha256sum installer.exe
# Output: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 installer.exe
If the hex string matches, the file is exactly what the publisher uploaded. If not, something changed — either in transit, on disk, or maliciously — and you should not trust the file.
REMEMBER
MD5 and SHA-1 are deprecated for security purposes (an attacker can construct two different files with the same hash). They're still fine for accidental-corruption checking. For security verification (download integrity from an untrusted network), always use SHA-256 or stronger.
base64base64 encodes binary data as ASCII text and decodes it back. Useful when you need to embed binary data in a text-only context — email attachments, JSON payloads, configuration files:
base64 image.png > image.b64 # encode to text
base64 -d image.b64 > restored.png # decode back to binary
echo "hello" | base64 # encode a string
echo "aGVsbG8K" | base64 -d # decode (note the trailing newline)
It's not encryption (anyone can decode base64 in two seconds); it's encoding. Don't confuse the two.
Let's wire this all together with a realistic scenario. Say you've downloaded a tool's source archive, want to verify it, extract it, look around, make a backup of one file before editing it, and then do a quick search-and-replace.
cd Downloads
sha256sum cool-tool-1.2.3.tar.gz
You compare the printed hash to the one on the project's website. They match. Good.
mkdir -p C:\Tools\cool-tool
cd C:\Tools\cool-tool
tar -xzf C:\Users\YourName\Downloads\cool-tool-1.2.3.tar.gz
ls
You look around:
cd cool-tool-1.2.3
find . -name "config*"
file config.ini
type config.ini
You spot a setting you want to change. Before editing, batch-edit with sed and keep a safety copy:
sed -i.orig 's|/old/path|/new/path|g' config.ini
That changes every occurrence of /old/path in config.ini to /new/path, keeping config.ini.orig as a safety copy. Want to confirm what changed?
diff config.ini.orig config.ini
Or summarize the file in some useful way — say, count how many times each section header appears:
awk '/^\[/ { count[$0]++ } END { for (k in count) print count[k], k }' config.ini | sort -rn
Later, when you're confident the new config works, clean up:
rm config.ini.orig
That entire workflow used sha256sum, mkdir, cd, tar, ls, find, file, type, sed, diff, awk, sort, and rm — every major tool we've covered, in service of a real goal. That's how shell work actually goes: a string of small, sharp commands, each one small enough to type in a few seconds, composed into something useful.
A handful of file commands we glossed over because they're either niche or covered better elsewhere:
cut, sort, uniq, tr, head, tail, rev, tac — text-manipulation tools that shine when you start piping things together. We'll cover them in Chapter 6 (Pipes and Redirection), where their power becomes obvious.nl, fold, fmt, pr — text formatting rather than text manipulation: number lines, wrap them, reflow paragraphs, paginate for printing. Also Chapter 6.du, df — disk usage and free space. Briefly: du -sh foldername shows total size of a folder; df shows disk usage per drive.tee — split output into a file and the terminal at the same time. Pipes territory; Chapter 6.watch — re-run a command periodically to see live changes. Useful for monitoring; minor enough to skip here.When you need any of the rest, help <command> will get you started, and man <command> will give you the full picture.
You can now create, copy, move, delete, find, search, replace, transform, and inspect anything on your filesystem. That's the beating heart of shell work. The next chapter — Chapter 5 — moves from files to state: variables, aliases, and the environment. We'll start customizing cshw to fit your habits, and you'll meet the special variables ($?, $result, $argc) that turn one-shot commands into reusable scripts.
Bring your .cshrc file (we'll create one if you don't have one yet). We're going to make this shell yours.