Awk cheatsheet

Sed Usage
# Syntax
sed [options] command [input-file]

# With pipeline
cat report.txt | sed 's/Nick/John/g'
Search for text
# Search for a string
sed -n '/hello/p' file.txt
# Case insensitive search
sed -n '/hello/Ip' file.txt
# Only output lines that do not match
sed -n '/hello/!p' file.txt
Change lines
# Insert text before line 5
sed '5i line number five' file.txt
# Insert before lines with "hello"
$ sed '/hello/i Example: ' file.txt
# Delete line 5-7 in file
sed '5,7d' file.txt

Option Example

OptionExampleDescription
-ised -ibak 's/On/Off/' php.iniBackup and modify input file directly
-Esed -E 's/[0-9]+//g' input-fileUse extended regular expressions
-nsed -n '3 p' config.confSuppress default pattern space printing
-fsed -f script.sed config.confExecute sed script file
-esed -e 'command1' -e 'command2' input-fileExecute multiple sed commands

Commands

CommandExampleDescription
psed -n '1,4 p' input.txtPrint lines 1-4
dsed '1,4 d' input.txtPrint lines except 1-4
wsed -n '1,4 w output.txt' input.txtWrite pattern space to file
ased '2 a new-line' input.txtAppend line after
ised '2 i new-line' input.txtInsert line before

Sed substitute command and flags

shell
sed 's/original-string/replacement-string/[flags]' [input-file]
FlagDescriptionExample
gGlobal substitutionsed 's/development/production/g' .env
1,2...Substitute the nth occurrencesed 's/latin1/utf8/2' locale.sql
pPrint only the substituted linesed -n 's/error_log = 0/error_log = 1/p' php.ini
wWrite only the substituted line to a filesed -n 's/One/Two/w output.txt' words.txt
iIgnore case while searchingsed 's/true/FALSE/i' config.php
eSubstitute and execute in the command linesed 's/^/ls -l /e' files.list
&Gets the matched patternsed 's/^.*/<&>/' index.xml
( ) \1 \2 \3Group using ( and ).
Use \1, \2 in replacement to refer the group
sed 's/([^,]*),([^,]*),([^,]*).*/\1,\3/g' words.txt