LinuxCommandLibrary

Text Processing

Substitute text in a file

$ sed 's/old/new/g' [file]
copy
$ sed -i 's/old/new/g' [file]
copy
$ sed -i 's/old/new/gI' [file]
copy

Delete lines matching a pattern

$ sed '/pattern/d' [file]
copy
$ sed -i '/^$/d' [file]
copy

Print specific lines

$ sed -n '5,10p' [file]
copy
$ sed -n '/pattern/p' [file]
copy

Extract fields from text

$ awk '{print $1}' [file]
copy
$ awk -F: '{print $1, $3}' [file]
copy
$ awk '{print NR, $0}' [file]
copy

Filter lines with awk conditions

$ awk '$3 > 100' [file]
copy
$ awk '/pattern/ {print $2}' [file]
copy
$ awk 'NR>=5 && NR<=10' [file]
copy

Sum a column of numbers

$ awk '{sum += $1} END {print sum}' [file]
copy

Sort lines

$ sort [file]
copy
$ sort -n [file]
copy
$ sort -r [file]
copy
$ sort -t: -k3 -n [file]
copy
$ sort -u [file]
copy

Filter duplicate lines

$ uniq [file]
copy
$ uniq -c [file]
copy
$ uniq -d [file]
copy
$ uniq -u [file]
copy
$ sort [file] | uniq -c | sort -rn
copy

Cut fields from text

$ cut -d: -f1 [file]
copy
$ cut -d',' -f1,3 [file]
copy
$ cut -c1-10 [file]
copy

Translate or delete characters

$ tr 'a-z' 'A-Z' < [file]
copy
$ tr -d '[:digit:]' < [file]
copy
$ tr -s ' ' < [file]
copy
$ tr '\n' ' ' < [file]
copy

Compare two files

$ diff [file1] [file2]
copy
$ diff -u [file1] [file2]
copy
$ diff -y [file1] [file2]
copy
$ comm [file1] [file2]
copy
$ cmp [file1] [file2]
copy

Merge lines of files

$ paste [file1] [file2]
copy
$ paste -d',' [file1] [file2]
copy
$ paste -s [file]
copy

Join files on a common field

$ join [file1] [file2]
copy
$ join -t: -1 1 -2 3 [file1] [file2]
copy

Format text into columns

$ column -t [file]
copy
$ column -t -s',' [file]
copy

Wrap text to a specific width

$ fmt -w 80 [file]
copy
$ fold -w 80 [file]
copy
$ fold -s -w 80 [file]
copy

Number lines

$ nl [file]
copy
$ nl -ba [file]
copy
$ cat -n [file]
copy

Count lines, words, and characters

$ wc [file]
copy
$ wc -l [file]
copy
$ wc -w [file]
copy
$ wc -c [file]
copy

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard