Sed is a text/string editor command-line tool.
Follow the most basic commands:
- sed ‘s/LOOKFOR/REPLACE/‘ file.txt
- reads the file, looks for a pattern and replaces it on a match.
- cat file.txt | sed ‘s/LOOKFOR/REPLACE/’
- piping the input to sed.
- cat file.txt | sed ‘s/LOOKFOR/REPLACE/’ output.txt
- piping the input and redirecting the output to a file.
- sed ‘s/LOOKFOR/REPLACE/’ file.txt > output.txt
- file input and output.
- cat file.txt | sed ‘s/LOOKFOR/REPLACE/g‘
- the global flag prevents stopping on the first match.
- sed -i ‘s/LOOKFOR/REPLACE/’ file.txt
- edits the original file in-place.
- cat file.txt | sed ‘s/[0-9]/(&)/g’
- & represents the matched string.
- cat file.txt | sed ‘s_[0-9]_(&)_g’
- using alternative delimiters.
- cat file.txt | sed ‘s/\//*/g’
- escaping special characters by adding a backslash before them.
- sed ‘s/[^0-9]/REPLACE/’ file.txt
- replaces anything that is not a number.
- sed ‘s/LOOKFOR/REPLACE/g;s/LOOKFOR/REPLACE/g’ file.txt
- applies multiple substitutions in one command, separated by a semicolon.
- sed -f replacements.txt file.txt
- loads patterns from a file (one per line).
- sed -n ‘s/LOOKFOR/REPLACE/g’ file.txt
- suppresses screen output.
- sed -n ‘s/LOOKFOR/REPLACE/pg’ file.txt
- outputs only lines that had matches.
- sed ‘s/LOOKFOR/REPLACE/Ig’ file.txt
- case-insensitive pattern matching.
- sed ‘/LOOKFOR/d‘ file.txt
- deletes matching lines.
- sed ‘1!{s/LOOKFOR/REPLACE/g;}‘ file.txt
- skips the first line.
- sed ‘4 q‘ file.txt
- reads only the first 4 lines, then quits.
- sed ‘5,$ d‘ file.txt
- deletes all lines from line 5 onward.
- sed ‘=‘ file.txt
- prints the line number before each line.
- sed ‘=’ file.txt | sed ‘N; s/\n/ /‘
- prints the line number at the beginning of each line.
- sed -n ‘=‘ file.txt
- prints only line numbers.
- sed ‘$=’ file.txt
- prints the line number of the last line (i.e. the total line count).
- sed ‘n;d‘ file.txt
- prints even-numbered lines.
- sed ‘1!n;d’ file.txt
- prints odd-numbered lines.
- sed -n ‘p;n;n‘ file.txt
- prints one line then skips the next two, and repeats.
- sed ‘/”[a-z]/ s/”/_/g’
- finds a pattern, then applies the substitution only on lines that match.
- sed ‘s/\([0-9]\)-\([0-9]\)/\2–\1/g’
- The parentheses define capture groups 1 and 2; their values are then placed in reverse order.
- Note: capture group “zero” (\0) represents the entire match.
- The parentheses define capture groups 1 and 2; their values are then placed in reverse order.
SOURCES
Excellent deep dive into all Sed functionality [Link]
Perl can also perform similar tasks with the following syntax:
perl -p -i -e 's#LOOKFOR#R#' myfile1 myfile2
BONUS
Command-line JSON processor jq combined with sponge:
jq '."attributeName" = "value"' /PATH/fileName.json | sponge /PATH/fileName.json