tips
85 tips Text processing
One command, setting or habit at a time about Text processing: what it does, the line to copy and a caveat or two.
Text processing 85
-
Change or delete one specific XML node in place, picked by XPath.
xmlstarlet ed -u '//item[@id="1"]/title' -v 'Changed' feed.xml -
Read single values from an XML file with an XPath, from the command line.
xmlstarlet sel -t -v '//item/title' -n feed.xml -
Limit ripgrep to some file types or skip noisy files with a glob.
rg 'apiKey' -g '!*.min.js' -g '!package-lock.json' -
Print the number of lines in a file, or the line numbers of matches, with sed.
sed -n '$=' access.log -
Turns JSON strings into single-quoted shell words that survive spaces and apostrophes.
jq -r '.files[] | @sh' data.json -
Takes only the first few results of a jq generator and quits early.
jq -n -c 'limit(3; range(1; 1000000000))' -
Passes any number of values from the shell to a jq filter as an array.
jq -n -c '$ARGS.positional' --args a "b c" -
Parses a string field that itself contains JSON, so you can filter into it.
echo '{"id":1,"payload":"{\"user\":\"ann\",\"tags\":[\"x\",\"y\"]}"}' | jq -c '.payload | fromjson | .tags' -
Replaces all matches of a pattern in the line or in one chosen column, and counts them.
echo 'cost: 1,50 and 2,25' | awk '{n=gsub(/,/,"."); print n": "$0}' -
Writes each line to a file named after a value in that line, such as a country code.
awk -F, 'NR>1 {print > ($2".csv")}' data.csv -
Extracts part of a string by start position and length, counting from 1.
echo 20261201 | awk '{print substr($0,1,4)"-"substr($0,5,2)"-"substr($0,7,2)}' -
Upper- or lowercases a match inside the replacement part of an s command in GNU sed.
echo 'hello world' | sed 's/.*/\U&/' -
Inserts a line of text after each line that matches a pattern.
printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5' -
Runs a filter on every key and value of a JSON object to rename or drop keys.
jq 'with_entries(.key |= ascii_upcase)' -
Catch a broken config before the program that reads it does.
jq empty config.json -
Find the exact route to a value without scrolling through nested output.
-
Add names from one export to records in another without writing a program.
jq -c --slurpfile u users.json ' -
Process a file that is too big for a normal jq run.
jq -cn --stream 'fromstream(1|truncate_stream(inputs))' big.json -
Convert dates once while parsing instead of all over your code.
const text = '{"createdAt":"2026-11-30T09:00:00Z","name":"x"}'; -
Find which file in an archive mentions a word, without extracting anything.
zipgrep db_host backup.zip -
Find the right manual or invoice by what is written in it.
pdfgrep -rin "warranty" ~/Documents -
Edit a field in place, using its current value, without rebuilding the document.
jq '.replicas |= . + 1' deploy.json -
Turn ordinary text lines into strings jq can split, filter and wrap.
cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' -
Sort records on a field and keep only the first few.
jq -c 'sort_by(-.mem) | .[:2] | map(.name)' containers.json -
Shows how awk turns decimals into whole numbers, and why 2.5 can become 2.
echo '2.5 3.7' | awk '{print int($1), int($2), sprintf("%.0f", $1)}' -
Flatten records into tab separated lines that classic text tools can handle.
jq -r '.[] | [.name, .mem] | @tsv' containers.json | sort -t$'\t' -k2 -n | column -t -
Compare two lists without sorting them first, line for line and exact.
grep -vxFf allowed.txt users.txt -
Splits fields on several different characters at once, using a regular expression as separator.
echo 'web1:8080,5' | awk -F'[:,]' '{print $1, $2, $3}' -
Check how wide a file is before you print it, wrap it or set a column width.
wc -L access.log -
Grabs the last field of each line, even when lines have a different number of fields.
echo /var/log/nginx/access.log | awk -F/ '{print $NF, $(NF-1)}' -
Find the stray carriage return, tab or odd byte that breaks a script or config.
head -n 3 config.env | od -c -
Find the entries that appear twice in a list, or the ones that appear once.
sort hosts.txt | uniq -d -
Remove a single field from a CSV or log without listing every field you want to keep.
cut -d, -f2 --complement people.csv -
Decode the middle part of a JWT to see its claims and expiry time.
echo "$TOKEN" | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson' -
Replace missing or null fields with a fallback value in jq output.
jq -r '.[] | "\(.name): \(.description // "no description")"' repos.json -
Replace the first occurrence in a file and leave every later one alone.
sed '0,/^port=/s//port=8081 #/' app.conf -
Pull one section out of a config or log, from a start line to an end line.
sed -n '/BEGIN backup/,/END backup/p' /var/log/app.log -
Count how many records share a value, straight from an API response.
jq -c 'group_by(.state) | map({state: .[0].state, count: length})' containers.json -
Remove duplicates based on one column, like keeping one line per host name.
sort -u -k1,1 logins.txt -
Take the last part of a path or line when the number of fields changes.
echo /srv/media/films/2024/clip.mkv | rev | cut -d/ -f1 | rev -
Fix the garbled characters in an old export by converting its encoding.
iconv -f latin1 -t utf-8 old.csv > new.csv -
Lists every line above a certain length with file name and line number.
awk 'length > 120 {print FILENAME ":" FNR ": " length}' *.py -
Split a long log or dump into separate files at every line that starts a new section.
csplit -s -z -f part- dump.sql '/^CREATE TABLE/' '{*}' -
Formats output into aligned columns with fixed widths and decimals.
printf 'nginx 12.5\npostgres 300\n' | awk '{printf "%-10s %8.1f MB\n", $1, $2}' -
Treats each paragraph as one record, so you can filter whole blocks instead of single lines.
awk 'BEGIN {RS=""} /[email protected]/' contacts.txt -
Joins two files on a shared column, like a small database lookup, in one awk command.
awk -F, 'NR==FNR {name[$1]=$2; next} FNR>1 {print $1, ($2 in name ? name[$2] : "unknown"), $3}' names.csv orders.csv -
Reflow ragged lines in notes, commit messages or a README to one width.
fmt -w 72 notes.txt -
Cut off a footer or trailing lines without counting how long the file is.
head -n -5 report.txt -
Drops every line that has no visible content, also lines with just spaces or tabs.
awk NF file.txt > clean.txt -
Totals a number column separately for each value in another column, like a GROUP BY.
awk -F, 'NR>1 {s[$2]+=$3} END {for (k in s) print k, s[k]}' orders.csv -
Find the config files where a setting is missing, not the ones where it is set.
grep -L 'Restart=' /etc/systemd/system/*.service -
Rebuilds every line with a new field separator, for turning aligned output into CSV.
printf 'a b c\n' | awk -v OFS=, '{print}' # a b c -
Reads the header row once and then selects columns by name instead of by number.
awk -F, 'NR==1 {for (i=1; i<=NF; i++) col[$i]=i; next} {print $col["amount"]}' orders.csv -
Prints a block of lines from one matching line up to and including another.
awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' bundle.pem -
Makes xargs split its input only at newlines, so names with spaces stay whole.
printf '%s\n' "holiday photo.jpg" "notes 2026.txt" | xargs -d '\n' -n1 echo -
Prints a file with tabs, line ends and control characters made visible.
cat -A docker-compose.yml -
Adds up all the numbers in one column of a file or command output.
awk -F, '{s+=$2} END {print s}' costs.csv -
Hands a value from your shell script to awk without breaking the quoting.
df -P | awk -v max="$limit" 'NR > 1 && $5+0 > max {print $6, $5}' -
Shows a few lines before and after every match, so you see what led up to an error.
grep -n -C 3 'segfault' /var/log/syslog -
Searches for text exactly as you typed it, without regex characters getting in the way.
grep -F '192.168.1.1' /var/log/nginx/access.log -
Limits a recursive grep to certain file types and skips folders like .git.
grep -rn --include='*.conf' --exclude-dir=.git 'listen' /etc/nginx -
Makes grep quit after the first match, or after any number you choose.
grep -n -m 1 'Out of memory' /var/log/syslog -
Prints only the matched text, like IP addresses, instead of the whole log line.
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/auth.log -
Only matches your search term as a whole word, not inside longer words.
grep -w port /etc/ssh/sshd_config -
Prints a file starting at a chosen line, for example to skip a CSV header.
tail -n +2 export.csv -
Swaps the slash in a sed replacement for another character, so paths stay readable.
sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf -
Prints only the lines between two line numbers, without opening an editor.
sed -n '210,218p' /etc/nginx/nginx.conf -
Converts tab characters into spaces, so YAML files with tab indentation load again.
expand -t 2 compose.yaml > compose.fixed.yaml -
Combines lines from two text files that share the same value in a key column.
join <(sort hosts.txt) <(sort roles.txt) -
Sorts lines on one chosen column, as text or as numbers, instead of on the whole line.
sort -t, -k3,3n people.csv -
Sorts a file and writes the result back into the same file without emptying it first.
sort -o list.txt list.txt -
Sorts version numbers like 1.9 and 1.10 in the order a person would expect.
printf '%s\n' 1.10.0 1.9.2 1.2.0 | sort -V -
Removes the hidden carriage returns that make Windows text files misbehave on Linux.
cat -E script.sh | head -
Prints just the line count of a file, so you can use it directly in a script.
wc -l < access.log -
Prints every jq result as one compact line, ready for loops and line-based tools.
jq -c '.[]' hosts.json -
Removes chosen keys or array items from JSON, so you can share a config without secrets.
jq 'del(.password)' config.json -
Collects every JSON value from the input into one array, so you can count, sum or merge them.
jq -s 'length' events.jsonl -
Wraps long lines to a chosen width and breaks them at spaces instead of in the middle of words.
echo "a very long sentence that keeps going and going" | fold -s -w 20 -
Lets grep use Perl-style patterns such as lookahead and \d, which the basic and extended syntax lack.
echo 'price=42 EUR' | grep -oP '\d+(?= EUR)' -
Adds line numbers to the output of a file or command, numbering empty lines as well.
nl -ba -w 4 -s ': ' /etc/hosts -
Prints JSON strings as plain text, so jq output works in scripts and loops.
echo '{"name":"nextdash"}' | jq -r '.name' -
Removes duplicate lines from a file and keeps the original order of the rest.
awk '!seen[$0]++' list.txt > unique.txt -
Edits a file in place with sed and saves the original as a backup copy.
sed -i.bak 's/old-host/new-host/g' config.txt -
Aligns the output of any command, or a CSV file, into readable columns.
mount | column -t -
Makes ripgrep also search ignored and hidden files, such as .env.
rg -u 'API_KEY' # also searches ignored files
Nothing in this filter yet.