Skip to content
RankCore.AI
← All posts

Five Linux Power Commands Pros Use Every Day: awk, xargs, sed, rsync, and strace

· Linux, awk, sed, rsync, strace

The short video above makes a sharp claim: you do not need a hundred Linux commands. You need five that working engineers use every day — awk, xargs, sed, rsync, and strace. This guide is the study version of that lesson. It walks each one-liner as you would type it, and flags every place the two-minute version simplifies or overreaches.

If you want the map of where files live on disk first, read our Linux file system guide. The commands below assume you can already find a log, a site tree, and a process in ps.

1. awk: pull columns out of text

awk reads input one record at a time, usually one line, splits each record into fields, and runs a short program against it. The everyday pattern is pattern { action }. Omit the pattern and the action runs on every line.

The video's first example, as shown on screen, is this complete pipeline:

awk '{print $1}' access.log \
  | sort | uniq -c | sort -nr | head -3

Walk it left to right.

awk '{print $1}' prints field 1 of every line. In the common Apache Combined Log Format and in typical nginx access logs, that first field is the client IP address. Always wrap the awk program in single quotes. If you write {print $1} unquoted, the shell expands $1 itself — usually to nothing — and awk prints whole lines instead of IPs.

sort puts identical IPs next to each other. uniq -c then counts adjacent duplicates; without the sort, two visits from the same address on different lines would not be merged. sort -nr sorts those counts as numbers, highest first. head -3 keeps the top three.

Nuance on the video: The spoken line is "pipe it into sort, uniq -c and head." The on-screen command also includes sort -nr, and that extra sort is required. uniq -c leaves the IPs in alphabetical order of the address, not in order of popularity. If you skip sort -nr, "top visitors" will not actually be the top.

A few field facts worth committing to memory: $0 is the whole line, $1 through $NF are the fields, NF is the number of fields, and NR is the record number. By default, fields split on runs of spaces and tabs. In a Combined Log line, the quoted request "GET /index.html HTTP/1.1" therefore becomes several fields, and the HTTP status usually lands in $9, not $7. If your log format is different, or a reverse proxy has prepended extra columns, field 1 may not be the client IP. Check one raw line before you trust a count.

awk can also filter. These are the next one-liners to learn after the video's example:

awk '$9 == 404 {print $7}' access.log        # missing paths
awk '{bytes += $NF} END {print bytes}' access.log

The language is standardized as awk; on most Linux systems the command is GNU awk (gawk). The programs above stay within everyday POSIX awk.

2. xargs: turn output into arguments

Most Unix commands write text to standard output. Many other commands, including rm, expect filenames as arguments, not as stdin. xargs is the bridge. It reads items from stdin and appends them to another command, packing as many as will fit on one command line, then running that command as many times as needed.

The video's first example:

find . -name '*.tmp' | xargs rm -v

find lists matching paths, one per line. xargs builds rm -v file1 file2 file3 ... and runs it. That is much faster than launching rm once per file, and it is what the video means by "all at once."

Nuance on "all at once": xargs does not promise a single invocation. It batches arguments up to a system limit (ARG_MAX). A huge list is split across several rm calls. The GNU xargs manual is explicit about this.

The video's pro tip is the important one, and it matches the GNU findutils documentation. Unix filenames may contain spaces, quotes, and even newlines. The default xargs delimiter is whitespace, so a file named draft notes.tmp becomes two arguments and rm will do the wrong thing. The safe pair is:

find . -name '*.tmp' -print0 \
  | xargs -0 rm -v

-print0 ends each path with a NUL byte. xargs -0 (or --null) reads those NUL-separated names literally. Use this whenever the names are not under your complete control.

Two more habits prevent accidents. First, preview: replace rm -v with echo and read the command lines before you delete anything. Second, GNU xargs supports -r (--no-run-if-empty); without it, some implementations still run rm with no filenames if find matches nothing. For this job, find . -name '*.tmp' -delete or find . -name '*.tmp' -exec rm -v {} + also works and avoids a pipe.

3. sed: edit a stream of text

sed, the stream editor, applies a list of edits to text as it flows past. It is not an interactive editor. The video's phrase "edits text without opening the file" is informal: sed does open the file, read it, and write a result. It just never loads a buffer for you to type in.

The on-screen command is:

sed -i 's/http/https/g' *.html

s/http/https/g is the substitute command: replace http with https on every match in the line (g means global, not "just the first"). *.html is expanded by the shell, not by sed, into a list of filenames. -i tells GNU sed to edit those files in place.

The video's safety tip is the right default: run the same command without -i first. sed then writes the edited text to standard output and leaves the files alone. Read that preview. Only then add -i.

Correction on the video: s/http/https/g is too broad. The string https already contains http, so an existing https://site.com becomes httpss://site.com. That is the opposite of what you wanted. Prefer a substitution that matches the scheme boundary:

sed 's|http://|https://|g' *.html

Or s/http:/https:/g. The | delimiters are legal in sed and avoid leaning-toothpick syndrome when the search term itself contains slashes.

A second portability note: -i is not POSIX. GNU sed accepts sed -i or sed -i.bak (the optional suffix writes a backup). BSD sed, including the sed on macOS, requires a suffix argument: sed -i '' for no backup, or sed -i .bak. If you share a script across Linux and macOS, do not assume sed -i alone will work.

Other practical limits: if *.html expands to thousands of names, you can hit the shell's argument limit. In that case, combine the last two tools: find . -name '*.html' -print0 | xargs -0 sed -i 's|http://|https://|g'. And always quote the program, just as with awk.

4. rsync: copy only what changed

rsync synchronizes files between two locations — two folders on one machine, or a local tree and a remote one over SSH. Its useful trick is that it tries not to resend data it does not have to. The video's command is:

rsync -avz --progress ./site/ \
  user@server:/var/www/site/

The flags, from the rsync manual:

  • -a (--archive) recurses and preserves almost all metadata: permissions, times, symbolic links, devices, and owner when you have the rights. It is the usual starting point for a site deploy or a backup.
  • -v (--verbose) lists what is being transferred.
  • -z (--compress) compresses data in flight, which helps on slower links and does little on a local disk copy.
  • --progress prints a per-file progress indicator. -P is the common shorthand for --partial --progress.

Nuance on "only copies what changed": By default rsync decides that from file size and modification time, not by reading every byte. That is fast and almost always right. If a file was edited in place without its timestamp changing, or you have reason to distrust timestamps, add --checksum (-c) and rsync will compare content. Do not turn that on by habit; it is more expensive.

The trailing slash is the part of the video that trips people in production, and the man page agrees with the on-screen rule. A trailing slash on the source means "copy the contents of this directory." No trailing slash means "copy the directory by name." So:

rsync -av ./site/  user@server:/var/www/site/
# contents of ./site land directly in /var/www/site/

rsync -av ./site   user@server:/var/www/site/
# you get /var/www/site/site/

The destination slash matters less in the usual "directory already exists" case, but the source slash is the one to look at twice. Tab completion in many shells adds a trailing slash to directory names, which is how this surprise usually happens.

Three more habits belong next to this command. Use --dry-run (-n) with -v and read the file list before a real deploy. Do not add --delete until you mean "make the destination look exactly like the source, including removals." And remember that a remote path like user@server:... uses SSH by default in modern rsync; you need working key or password access, and you are only as safe as that account's permissions on the far side.

5. strace: watch the system calls

When a process talks to the kernel — opening a file, reading, writing, creating a socket, connecting to a port — that request is a system call. strace prints those calls as they happen. The video saves it for last because it answers a question logs often cannot: what is this process doing right now?

The on-screen session is:

sudo strace -p 4321

-p attaches to an already running process by PID. You usually need elevated privileges to do that (hence sudo), or a kernel policy such as kernel.yama.ptrace_scope that allows it. The attach uses ptrace, and the process may pause briefly. In the video, the interesting lines are a connect() to port 5432 that returns -1 ECONNREFUSED (Connection refused). 5432 is the conventional port for PostgreSQL, so "the database is down" is a fair first reading of that trace.

Nuance on "the database is down": ECONNREFUSED means the TCP stack got a refusal — typically a RST — for that address and port. The usual cause is that nothing is listening there: the database process is stopped, it is bound to a different port or a different host, or a local firewall is rejecting the SYN. It is not the same as a timeout (ETIMEDOUT), which often means packets were dropped, and it is not "the host is unreachable." Confirm with ss -lptn 'sport = :5432' or pg_isready before you declare the database dead.

strace is noisy. Once you know you care about the network, narrow it:

sudo strace -f -e trace=network -p 4321
# or even tighter:
sudo strace -f -e connect -p 4321

-f follows forks and new threads, which you want for most servers. -s raises the string length so request bodies are not truncated. -o trace.log writes the output to a file. And be aware of the cost: tracing every syscall of a busy process can slow it down, and some production environments forbid ptrace on purpose.

You can also start the program under strace instead of attaching: strace -f -e network ./myapp. Use attach when the process is already stuck.

6. Flags and patterns worth adding next

Once the five one-liners from the video work, these are the next options you will actually use.

awk field separators. The default split on whitespace is fine for Combined Log IPs, but CSV-ish or colon-separated files need an explicit separator. awk -F: '{print $1, $3}' /etc/passwd prints usernames and UIDs. Inside a program, set FS in BEGIN and OFS if you want a different output separator: awk 'BEGIN{FS=":"; OFS="\t"} {print $1,$3}' /etc/passwd. BEGIN runs once before any line, END once after the last, which is how running totals such as bytes += $10 get printed only at the end.

awk and grep together. grep is still the right first filter when you only care about lines that contain a string: grep ' 500 ' access.log | awk '{print $1}'. Use awk's own pattern when the test is a field comparison, a numeric check, or a regular expression on one column: awk '$9 >= 500 {print $1, $7, $9}'.

xargs argument control. -n 1 forces one argument per command, useful when the target tool cannot take multiple paths. -I {} (or another placeholder) lets you put the argument in the middle of a command, not only at the end: find . -name '*.md' -print0 | xargs -0 -I {} cp {} /backup/. -P runs several batches in parallel; use it only for tools that are safe to overlap, and start with a small number. xargs -0 -t prints each constructed command before running it — a slightly better preview than echo when flags are involved.

sed addresses and several edits. A command can be limited to matching lines: sed -n '/^Error/p' app.log is a sed-flavored grep (the -n suppresses automatic printing, p prints the selected lines). sed '1,20s/foo/bar/' edits only the first twenty lines. Multiple expressions stack with -e or a semicolon: sed -e 's|http://|https://|g' -e '/<!-- debug -->/d'. If you use GNU -i.bak, you keep a backup next to each file and can diff or restore it.

rsync includes, excludes, and deletes. --exclude '.git' and --exclude 'node_modules' keep heavy or secret trees off the wire. --delete makes the destination match the source, including removals; that is irreversible on the destination, so it always follows a dry-run. If a transfer is interrupted, run the same command again; rsync will pick up remaining files. -a does not copy ACLs or extended attributes unless you add -A and -X.

strace of files, not only sockets. The same attach that caught ECONNREFUSED will also show openat(..., "config.yml", ...) = -1 ENOENT when a process looks for a file in the wrong directory, or EACCES when permissions are wrong. strace -e openat,stat,connect -p PID is a practical starting filter. If the process forks a child that does the real work, you will miss it without -f.

7. How the five fit together

These tools are more valuable in combination than in isolation. A realistic morning:

  1. A site is slow or erroring. awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head shows a spike of 502s.
  2. You attach strace -e connect -p to the app and see ECONNREFUSED on 5432. The database is not accepting connections.
  3. After the database is back, you clean leftover temp files with find /var/tmp -name '*.tmp' -print0 | xargs -0 rm -v.
  4. You fix a hard-coded http:// in the templates, previewing with sed, then editing in place with a precise pattern.
  5. You publish with rsync -avz --dry-run ./site/ user@server:/var/www/site/, read the list, then run it for real.

None of that requires a new framework. It requires being fluent with the five commands in the video.

8. A short lab

Use a scratch directory, not a production tree.

  1. Create a tiny access.log with a few Combined Log lines (the documentation addresses 192.0.2.1, 198.51.100.1, and 203.0.113.1 are safe). Run the awk pipeline and confirm the counts.
  2. Create good.tmp and my file.tmp. Run find . -name '*.tmp' | xargs echo and notice how the spaced name splits. Repeat with -print0 and xargs -0 echo.
  3. Put http://example.com and https://example.com in index.html. Run sed 's/http/https/g' and see httpss. Then run sed 's|http://|https://|g' and confirm only the first URL changes.
  4. rsync -avn site/ dest/ and rsync -avn site dest/ into an empty folder. Compare the resulting trees.
  5. In one terminal, start something that connects to port 5432 while nothing is listening (psql or a one-line Python socket.create_connection). In another, strace -e connect it and find ECONNREFUSED.

If you can do those five steps without notes, you have the video at working depth.

9. FAQ

Is awk better than cut? cut -d' ' -f1 can grab a column too, but it is weaker on repeated whitespace and cannot add filters or running totals. awk is the better default once the line is more than a simple delimiter split.

Why did xargs delete the wrong files? Almost always a name with a space, quote, or newline, or a glob that matched too much. Use -print0/-0, and preview with echo.

Can I use sed in place on macOS the same way? Not with bare -i. Use sed -i '' 's|http://|https://|g' file on BSD sed, or install GNU sed as gsed.

Does rsync overwrite newer files on the destination? By default, yes, if the source looks like it has changed. --update (-u) skips destination files that are already newer. --dry-run first.

Is strace safe on a production process? It is a debugging tool. It can slow the process, and attaching it requires ptrace rights. Prefer a staging attach, or a tight -e filter and a short window, and know your company's policy.

10. A compact list of mistakes these one-liners invite

  • Forgetting to quote '{print $1}' so the shell eats $1.
  • Running uniq -c without sorting first, or omitting sort -nr and calling the result "top visitors."
  • Assuming field 1 is always an IP. Confirm against one raw log line and against your server's documented format.
  • find ... | xargs rm on names that may contain spaces, quotes, or newlines. The video already gives the fix: -print0 and xargs -0.
  • Treating "xargs runs it all at once" as a guarantee of one process. It batches at ARG_MAX.
  • sed 's/http/https/g' rewriting https:// to httpss://.
  • sed -i copied from a Linux box onto macOS, where BSD sed expects a suffix argument.
  • A trailing slash typo on an rsync source, which silently creates an extra directory on the destination.
  • Adding rsync --delete without --dry-run, or assuming -a also copies ACLs.
  • Assuming rsync compared file bytes when it only compared size and mtime.
  • Reading ECONNREFUSED on port 5432 as proof the database host is down, rather than "nothing accepted this TCP connection."
  • Running strace -p without -f on a process that delegates work to children, or leaving an unfiltered trace on a hot production process.

11. Interview questions

"How do you find the noisiest IP in an access log?" The strong answer is the video's pipeline, plus why each stage is there: extract, sort so uniq can count, sort numerically descending, take the head. Mention that field 1 is format-dependent.

"How do you delete files that find lists, safely?" -print0 piped to xargs -0, or find -delete / -exec ... {} +. Calling out spaces and newlines is the difference between a junior and a careful answer.

"A process hangs with no log line. What do you do?" Attach strace (or perf, or an application debugger). Look for a blocking syscall: a connect, a read on a socket, a futex wait. ECONNREFUSED on the database port is one of the cleanest possible findings.

12. Summary

  • awk reads lines, splits fields, and prints or filters them. awk '{print $1}' access.log | sort | uniq -c | sort -nr | head is the classic top-talkers pipeline; the sort -nr is not optional.
  • xargs turns stdin into command arguments, in batches. For filenames, pair find -print0 with xargs -0.
  • sed applies stream edits. Preview without -i. Do not use s/http/https/g if the file may already contain https; match http:// or http:. Remember that -i differs on GNU and BSD sed.
  • rsync synchronizes trees and, by default, skips files whose size and timestamp have not changed. A trailing slash on the source copies contents; without it, you copy the directory itself. Dry-run before you deploy.
  • strace shows system calls. strace -p PID attaches to a running process. connect(... 5432 ...) = -1 ECONNREFUSED means nothing accepted that TCP connection; "database down" is a hypothesis you should then confirm.

Follow @rankcore.ai, and read more on blog.rankcore.ai.

Want to go deeper?

Our step-by-step video courses turn these ideas into results.

See courses

Comments

Sign in or create a free account to join the discussion.

No comments yet — be the first.