grep/sed/gawk/awk/tr/cut

References:

Good utilities for extracting stuff from text

Print lines containing pattern
sed -n '/pattern/p'
Print line lineno
sed -n 'lineno p'
Do both of the above
sed -ne 'lineno p' -e '/pattern/ p'
Print two lines lineno1 and lineno2
sed -ne 'lineno1 p' -e 'lineno2 p'
Print a file with line numbers
awk '{ print FNR, $0 }'
Print columns 1,2,and 7
awk '{ print $1, $2, $7 }'

A range is two addresses separated by a comma. /pattern1/ , /pattern2/

Can't use alternation with sed but you can with grep

Print lines containing either of two patterns
egrep pattern1 | pattern2
Ignore comment lines
grep -v "^#"
Ignore blank lines
sed /^$/d
Remove all newlines and carriage returns from a line of text
tr -d '\r\n'
Replace all newlines and carriage returns with a space
tr '\r\n' '   '

awk will not accept parameters until after it has opened the input file and that doesn't happen until after the BEGIN block has finished. If you want to use awk as a calculator with no input file you can build the command string in advance and then run it with eval:
a=79
b="awk 'BEGIN {print $a / 3}'"
c=$(eval $b)
echo $c --> 26.3333


Bash string extractions and other manipulations

if [[ "$string" =~ $substring ]]; then

String length

${#string}
or
expr length $string

Length of Matching Substring at Beginning of String

expr match "$string" '$substring'
$substring is a regular expression.

Index - Numerical position in $string of first character in $substring that matches.

expr index $string $substring

Substring Extraction - Extracts substring from $string at $position.

${string:position}
If the $string parameter is "*" or "@", then this extracts the positional parameters, [1] starting at $position

Extracts $length characters of substring from $string at $position.

${string:position:length}
Extracts $length characters of substring from $string at $position.


Other neat stuff

List all files in /etc that start with 'p' and end with 'd'
run-parts --list --regex '^p.*d$' /etc

Send mail to the Webmaster

logo This site best viewed with a browser
Warning: This is a Debian centric site
Many thanks to Debra and Ian Murdock for making Debian possible
First created Apr 22, 2008 ~ Last revised January 25, 2010

Valid XHTML 1.0 Strict Valid CSS!