RegexRecipes

From Genunix

Contents

perl

Turn every n lines into one line


  • perl -ne 'if($.%n !=0) {chomp;} print $_;' filename

Search for text between the lines that contain MB00251 and MB00598


  • perl -ne 'print if /MB00251/ .. /MB00598/'

Print line -n of filename


  • perl -ne 'if($.==n){print;exit}' filename

vi

Remove ^M

  •  :1,$ s/^v^m//g

Add hashes in front of every line

  •  :1,$ s/\(.*\)/#\1/

ed

Deletes the first line containing "regular"

  • /regular/d

globally deletes all lines containing "regular"

  • g/regular/d

Replaces the first occurrence of "regular" with "complex" on current line

  • s/regular/complex/

Globally replaces all occurrences of "regular" with "complex" on current line

  • s/regular/complex/g

Globally replaces all occurrences of "regular" with "complex"

  • g/regular/s/regular/complex/g

sed

Globally replaces all occurrences of "regular" with "complex"

  • s/regular/complex/
    • ie: sed 's/regular/complex/' filename

Outputs those lines that contain "regular"

  • sed -n -e 's/regular/complex/' filename

Links

awk

Print the first field of everyline in file "filename"

  • awk '{ print $1 }' filename

===Match all lines that contain regular expression "regular"

  • awk -F, '/regular/ { print $1 }' list
    • ("-F", change field separators to a comma)

grep

Print all lines that either do not begin with the "#"(hash) character or aren't blank lines


(Useful when you wish to view a config file without the comments)

  • egrep -v "^#|^$"

regex

Replace IP address "176.161.12.131" with "176.161.12.134"

  • 1,$ s/176\.161\.12\.131;/168\.161\.12\.131;176\.161\.12\.134;/g