2/1/10

Grep replacement for binary files / Script

Example 10-7. A grep replacement for binary files

    #!/bin/bash
    # bin-grep.sh: Locates matching strings in a binary file.
   
    # A "grep" replacement for binary files.
    # Similar effect to "grep -a"
   
    E_BADARGS=65
    E_NOFILE=66
   
  if [ $# -ne 2 ]
  then
     echo "Usage: `basename $0` string filename"
     exit $E_BADARGS
   fi
  
   if [ ! -f "$2" ]
   then
     echo "File \"$2\" does not exist."
     exit $E_NOFILE
   fi 
  
  
   for word in $( strings "$2" | grep "$1" )
   # The "strings" command lists strings in binary files.
   # Output then piped to "grep", which tests for desired string.
   do
     echo $word
   done
 
 # As S.C. points out, the above for-loop could be replaced with the simpler
 #    strings "$2" | grep "$1" | tr -s "$IFS" '[\n*]'
 
 # Try something like  "./bin-grep.sh mem /bin/ls"  to exercise this script.
   exit 0

 

<http://www.faqs.org/docs/abs/HTML/loops.html#FILEINFO>



Add ISCSI FileSystem

iSCSI Configuration

  1. iSCSI startup using the init script or manual start-up. You need to edit and configure iSCSI via /etc/iscsi/iscsid.conf file
  2. Discover targets.
  3. Automate target logins for future system reboots.
  4. You also need to obtain iSCSI username, password and storage server IP address target host)

Step  1: Configure iSCSI

Open /etc/iscsi/iscsid.conf with vi text editor:
# vi /etc/iscsi/iscsid.conf
Setup username and password:
node.session.auth.username = My_ISCSI_USR_NAME
node.session.auth.password = MyPassword
discovery.sendtargets.auth.username = My_ISCSI_USR_NAME
discovery.sendtargets.auth.password = MyPassword
Where,
• node.session.* is used to set a CHAP username and password for initiator authentication by the target(s).
• discovery.sendtargets.* is used to set a discovery session CHAP username and password for the initiator authentication by the target(s)
You may also need to tweak and set other options. Refer to man page for more information. Now start the iscsi service:
# /etc/init.d/iscsi start



Step 2: Discover targets


Now use iscsiadm command, which is a command-line tool allowing discovery and login to iSCSI targets, as well as access and management of the open-iscsi database. If your storage server IP address is 192.168.1.5, enter:
# iscsiadm -m discovery -t sendtargets -p 192.168.129.1
# /etc/init.d/iscsi restart
Now there should be a block device under /dev directory. To obtain new device name, type:
# fdisk -l
or
# tail -f /var/log/messages
/dev/sdb is my new block device.


Step 3: Format and Mount iSCSI Volume


You can now partition and create a filesystem on the target using usual fdisk and mkfs.ext3 commands:
# fdisk /dev/sdb
# mkfs.ext3 /dev/sdb1
Tip: If your volume is large size like 1TB, run mkfs.ext3 in background using nohup:
# nohup mkfs.ext3 /dev/sdb1 &

Mount new partition:
# mkdir /mnt/iscsi
# mount /dev/sdb1 /mnt/iscsi



Step 4: Mount iSCSI drive automatically at boot time


First make sure iscsi service turned on at boot time:

# chkconfig iscsi on
Open /etc/fstab file and append config directive:
/dev/sdb1 /mnt/iscsi ext3 _netdev 0 0

Save and close the file.

Advanced Bash Scripting link - Notes

Changes all filenames in working directory to lowercase.

   1 #! /bin/bash
   2 #
   3 # Changes every filename in working directory to all lowercase.
   4 #
   5 # Inspired by a script of John Dubois,
   6 # which was translated into into Bash by Chet Ramey,
   7 # and considerably simplified by Mendel Cooper, author of this document.
   8
   9
  10 for filename in *                # Traverse all files in directory.
  11 do
  12    fname=`basename $filename`
  13    n=`echo $fname | tr A-Z a-z`  # Change name to lowercase.
  14    if [ "$fname" != "$n" ]       # Rename only files not already lowercase.
  15    then
  16      mv $fname $n
  17    fi
  18 done 
  19
  20 exit 0
  21
  22
  23 # Code below this line will not execute because of "exit".
  24 #--------------------------------------------------------#
  25 # To run it, delete script above line.
  26
  27 # The above script will not work on filenames containing blanks or newlines.
  28
  29 # Stephane Chazelas therefore suggests the following alternative:
  30
  31
  32 for filename in *    # Not necessary to use basename,
  33                      # since "*" won't return any file containing "/".
  34 do n=`echo "$filename/" | tr '[:upper:]' '[:lower:]'`
  35 #                             POSIX char set notation.
  36 #                    Slash added so that trailing newlines are not
  37 #                    removed by command substitution.
  38    # Variable substitution:
  39    n=${n%/}          # Removes trailing slash, added above, from filename.
  40    [[ $filename == $n ]] || mv "$filename" "$n"
  41                      # Checks if filename already lowercase.
  42 done
  43
  44 exit 0

////////////////////////////////////////////////////

du: DOS to UNIX text file conversion.

   1 #!/bin/bash
   2 # du.sh: DOS to UNIX text file converter.
   3
   4 E_WRONGARGS=65
   5
   6 if [ -z "$1" ]
   7 then
   8   echo "Usage: `basename $0` filename-to-convert"
   9   exit $E_WRONGARGS
  10 fi
  11
  12 NEWFILENAME=$1.unx
  13
  14 CR='\015'  # Carriage return.
  15 # Lines in a DOS text file end in a CR-LF.
  16
  17 tr -d $CR < $1 > $NEWFILENAME
  18 # Delete CR and write to new file.
  19
  20 echo "Original DOS text file is \"$1\"."
  21 echo "Converted UNIX text file is \"$NEWFILENAME\"."
  22
  23 exit 0

http://www.faqs.org/docs/abs/HTML/index.html

P.S. The unalias command removes a previously set alias.

MSI / MS Installer error code 2230

Internal error 2203. c:\windows\installer\xxxxx.ipi, -2147024629
Document ID: CTX104619 / Created On: Sep 7, 2004 / Updated On: Sep 29, 2004
Average Rating: 1 (8 ratings)
View products this document applies to link to products this document applies to

Symptoms

When trying to install/uninstall a citrix hotfix, installing/uninstalling the server software or when adding or removing some components of the server software one may receive the following error:

Internal error 2203. c:\windows\installer\xxxxx.ipi, -2147024629



Resolution

Ensure the path of the administrator’s user variables in the system properties of the temp and tmp variables are as follows:

TEMP:%USERPROFILE%\Local Settings\Temp

TMP:%USERPROFILE%\Local Settings\Temp

This document applies to:

* MetaFrame Presentation Server 3.0 for Microsoft Windows 2000
* MetaFrame Presentation Server 3.0 for Microsoft Windows 2003
* MetaFrame XP 1.0 for Microsoft Windows 2000
* MetaFrame XP 1.0 for Microsoft Windows 2003

http://support.citrix.com/article/CTX104619 

Microsoft Word 2000 HTML Mess Cleaner

It is well-known that Microsoft Word is a lot less than perfect when it comes to generating HTML-code. The "Save as web page"-function in Microsoft Word generates files that are about ten times as large as they should be. This is because the code is filled with a lot of page formatting tags in order to be able to present the document in Microsoft Office-programs (Word+Powerpoint). This "code bloat" is useless in a web context and potentially harmful to presentation in any other browser than Internet Explorer.

The problem not only arises when using the "Save as web page"-option. You get the same mess when copying text from Word to a Wysiwyg-editor (i.e. Frontpage) or in many cases to a Content Management System.

The solution: Remove the clutter from the HTML code automatically:
http://www.algotech.dk/word-html-cleaner-input.htm

More Free MS Word HTML cleaners:

AD Attribs

AD attributes List
General Tab
Display Name
Attribute Name
Example Value
First Name
givenName
John
Initials
initials
JS
Last Name
sn
Smith
Display Name
displayName
John Smith
Description
description
Sales Manager
Office
physicalDeliveryOfficeName
London Office
Telephone Number
telephoneNumber
0123 456 789
Telephone Number (Other)
otherTelephone
0123 4457 89
Email
mail
JSmith@domain.com
Web Page
wWWHomePage
Web Page (Other)
url
Password
password
JohnsPass321
Destination OU
destinationOU
"OU=Sales,DC=Domain,DC=Com"
Common Name
CN
John Smith or %lastname%
%firstname%
Modify User if already exists
Modify
True or False
Delete User
Delete
True or False
Address Tab
Display Name
Attribute Name
Example Value
Street
streetAddress
10 Downing St;London
(Use a semi-colon for carriage
return)
PO Box
postOfficeBox
Po Box 1
City
l (Lowercase L)
London
State/Province
st
New York
Zip/Postal Code
postalCode
614415
Country
c
GB, DE, US etc
Group Tab
Display Name
Attribute Name
Example Value
Group
memberOf
"CN=ManagersGroup,DC=Domain,DC=Com"
Account Tab
Display Name
Attribute Name
Example Value
User Logon Name
userPrincipalName
JSmith@domain.com
User Logon Name (Pre W2K)
sAMAccountName
JSmith (This attribute is
essential and must be in the import file)
User must change password at next
logon
mustChangePassword
True or False
User cannot change password
userCannotChangePassword
True or False
Account is Disabled
accountDisabled
True or False
Use DES encryption
useDES
True or False
Do not require kerberos
preauthentication
notRequireKerberos
True or False
Password never expires
passwordNeverExpires
True or False
Account is trusted for delegation
trustedForDelegation
True or False
Store password using reversable
encryption
passwordReversable
True or False
Smart card is required for
interactive logon
smartCardRequired
True or False
Account is sensitive and cannot
be delegated
sensitiveForDelegation
True or False
Account Expires (use same date
format as server)
expires
01/01/2007
Profile Tab
Display Name
Attribute Name
Example Value
Profile Path
profilePath
Login Script
scriptPath
logon.bat
Home Folder (local or UNC, see
notes above)
homeFolder
Create Home Folder and Set
Permissions
createHomeDirectory
True
Telephones Tab
Display Name
Attribute Name
Example Value
Home
homePhone
660 123 122
Home (Other)
otherHomePhone
0661 123 122
Pager
pager
1234
Pager (Other)
otherPager
123
Mobile
mobile
120 456 789
Mobile (Other)
otherMobile
121 456 789
Fax
facsimileTelephoneNumber
122 456 789
Fax (Other)
otherFacsimile
TelephoneNumber
0123 456 789
IP Phone
ipPhone
01IP
IP Phone (Other)
otherIpPhone
432493809
Notes
info
General information (Use a
semi-colon for carriage return)
Organization Tab
Display Name
Attribute Name
Example Value
Title
title
Manager
Department
department
Sales
Company
company
Big Corp
Manager
manager
"CN=SJobs,OU=Managers,DC=Domain,DC=Com"
Employee ID
employeeID
Employee Type
employeeType
Employee Number
employeeNumber
Car License
carLicense
Division
division
Middle Name
middleName
Room Number
roomNumber
Assistant
assistant
jpegPhoto
jpegPhoto
E:\photos\%username%.jpg
(25KB or less, 200x200 pixels or
less)
Exchange Tab
Display Name
Attribute Name
Example Value
Create Mailbox for User
mailboxEnabled
True or False, Required when
creating a mailbox.
Alias
mailNickname
Jsmith *Required
Simple Display Name
displayNamePrintable
Jsmith *Required
Email addresses
proxyAddresses
SMTP:JSmith@doamin.com
multiple
addresses?
Forward to
altRecipient
CN=User2,OU=Managers,DC=Domain,DC=Com
Deliver & Forward
deliverAndRedirect
True
Use MAPI Rich Text
mAPIRecipient
True or False
Hide From Address Lists
msExchHideFromAddressLists
True or False
Exchange Store
ExchangeStore
Mail-Enable User
mailEnabled*
True or False
*Do not use with mailboxEnabled
above.
External Address
targetAddress
Required when mail-enabling a
user.
Exchange
Attributes
Display Name
Attribute Name
Example Value
extensionAttribute1
extensionAttribute1
extensionAttribute2
extensionAttribute2
extensionAttribute3
extensionAttribute3
extensionAttribute4
extensionAttribute4
extensionAttribute5
extensionAttribute5
extensionAttribute6
extensionAttribute6
extensionAttribute7
extensionAttribute7
extensionAttribute8
extensionAttribute8
extensionAttribute9
extensionAttribute9
extensionAttribute10
extensionAttribute10
extensionAttribute11
extensionAttribute11
extensionAttribute12
extensionAttribute12
extensionAttribute13
extensionAttribute13
extensionAttribute14
extensionAttribute14
extensionAttribute15
extensionAttribute15
Terminal
Services Tab
Display Name
Attribute Name
Example Value
Profile Path
TSProfilePath
Home Folder
TSHomeFolder
Create Home Folder
TSCreateHomeDirectory
True or False
Deny Logon
TSDenyLogon
True or False
Dial-In Tab
Display Name
Attribute Name
Example Value
Allow Dial-In Access
msNPAllowDialin
True or False
© 2009 Dovestones Software. All rights reserved.

View the current operations master role holders

Once an operations master role has been transferred, it should be verified that the transfer has occurred successfully throughout the domain. The change must be replicated to all relevant domain members in order to truly take effect.
To view the current operations master role holders, use Ntdsutil.exe with the roles option. This option displays a list of all current role holders.
Administrative Credentials
To perform this procedure, you must be logged on as a User or an Administrator.
To view the current operations master role holder
    1. Click Start, click Run, type ntdsutil, and then press ENTER.
    2. At the ntdsutil: prompt, type roles and press ENTER.
    3. At the fsmo maintenance: prompt, type connections and press ENTER.
    4. At the server connections: prompt, type connect to server servername (where servername is the name of the domain controller that belongs to the domain containing the operations masters).
    5. After receiving confirmation of the connection, type quit and press ENTER to exit this menu.
    6. At the fsmo maintenance: prompt, type select operation target and press ENTER.
    7. At the select operations target: prompt, type list roles for connected server and press ENTER.
The system responds with a list of the current roles and the Lightweight Directory Access Protocol (LDAP) name of the domain controllers currently assigned to host each role.
    8. Type quit and press ENTER to exit each prompt in Ntdsutil.exe. Type quit and press ENTER at the ntdsutil: prompt to close the window.

Decommissioning a Domain Controller

To  verify  communication with other domain controllers
    1. Open a Command Prompt
    2. Type the following command and then press ENTER:
netdiag /test:dsgetdc




http://technet.microsoft.com/en-us/library/cc755937.aspx

Standard Input and Output Redirection

The shell and many UNIX commands take their input from standard input (stdin), write output to standard output (stdout), and write error output to standard error (stderr). By default, standard input is connected to the terminal keyboard and standard output and error to the terminal screen.
The way of indicating an end-of-file on the default standard input, a terminal, is usually .
Redirection of I/O, for example to a file, is accomplished by specifying the destination on the command line using a redirection metacharacter followed by the desired destination.
 

C Shell Family
Some of the forms of redirection for the C shell family are:
Character
Action
>
Redirect standard output
>&
Redirect standard output and standard error
<
Redirect standard input
>!
Redirect standard output; overwrite file if it exists
>&!
Redirect standard output and standard error; overwrite file if it exists
|
Redirect standard output to another command (pipe)
>>
Append standard output
>>&
Append standard output and standard error
The form of a command with standard input and output redirection is:
% command -[options] [arguments] < input file  > output file

If you are using csh and do not have the noclobber variable set, using > and >& to redirect output will overwrite any existing file of that name. Setting noclobber prevents this. Using >! and >&! always forces the file to be overwritten. Use >> and >>& to append output to existing files.
Redirection may fail under some circumstances: 1) if you have the variable noclobber set and you attempt to redirect output to an existing file without forcing an overwrite, 2) if you redirect output to a file you don't have write access to, and 3) if you redirect output to a directory.
Examples:
    % who > names
        Redirect standard output to a file named names
    % (pwd; ls -l) > out
        Redirect output of both commands to a file named out
    % pwd; ls -l > out
        Redirect output of ls command only to a file named out
Input redirection can be useful, for example, if you have written a FORTRAN program which expects input from the terminal but you want it to read from a file. In the following example, myprog, which was written to read standard input and write standard output, is redirected to read myin and write myout:
% myprog < myin > myout

You can suppress redirected output and/or errors by sending it to the null device, /dev/null. The example shows redirection of both output and errors:
% who >& /dev/null

To redirect standard error and output to different files, you can use grouping:
% (cat myfile > myout) >& myerror

Bourne Shell Family
The Bourne shell uses a different format for redirection which includes numbers. The numbers refer to the file descriptor numbers (0 standard input, 1 standard output, 2 standard error). For example, 2> redirects file descriptor 2, or standard error. &n is the syntax for redirecting to a specific open file. For example 2>&1 redirects 2 (standard error) to 1 (standard output); if 1 has been redirected to a file, 2 goes there too. Other file descriptor numbers are assigned sequentially to other open files, or can be explicitly referenced in the shell scripts. Some of the forms of redirection for the Bourne shell family are:
Character
Action
>
Redirect standard output
2>
Redirect standard error
2>&1
Redirect standard error to standard output
<
Redirect standard input
|
Pipe standard output to another command
>>
Append to standard output
2>&1|
Pipe standard output and standard error to another command
Note that < and > assume standard input and output, respectively, as the default, so the numbers 0 and 1 can be left off. The form of a command with standard input and output redirection is:
$ command -[options] [arguments] < input file > output file

Redirection may fail under some circumstances: 1) if you have the variable noclobber set and you attempt to redirect output to an existing file without forcing an overwrite, 2) if you redirect output to a file you don't have write access to, and 3) if you redirect output to a directory.
Examples:
    $ who > names
        Direct standard output to a file named names
    $ (pwd; ls -l) > out
        Direct output of both commands to a file named out
    $ pwd; ls -l > out
        Direct output of ls command only to a file named out
Input redirection can be useful if you have written a program which expects input from the terminal and you want to provide it from a file. In the following example, myprog, which was written to read standard input and write standard output, is redirected to read myin and write myout.
$ myprog < myin > myout

You can suppress redirected output and/or error by sending it to the null device, /dev/null. The example shows redirection of standard error only:
$ who 2> /dev/null

To redirect standard error and output to different files (note that grouping is not necessary in Bourne shell):
$ cat myfile > myout 2> myerror



A. Bash and other modern shell provides I/O redirection facility. There are 3 default standard files (standard streams) open:
[a] stdin - Use to get input (keyboard) i.e. data going into a program.
[b] stdout - Use to write information (screen)
[c] stderr - Use to write error message (screen)
Understanding I/O streams numbers
The Unix / Linux standard I/O streams with numbers:
Handle
Name
Description
0
stdin
Standard input
1
stdout
Standard output
2
stderr
Standard error
Redirecting the standard error stream to a file
The following will redirect program error message to a file called error.log:
$ program-name 2> error.log
$ command1 2> error.log
Redirecting the standard error (stderr) and stdout to file
Use the following syntax:
$ command-name &>file
OR
$ command > file-name 2>&1
Another useful example:
# find /usr/home -name .profile 2>&1 | more
Redirect stderr to stdout
Use the command as follows:
$ command-name 2>&1

More VI

vi Cheat Sheet

This document is a vi cheat sheet, designed to be kept nearby while using the vi editor. In general, vi commands follow the convention of "one from column A and one from column B", using the two tables below, Operators and Operands, as columns A and B.
Numeric arguments may prefix any operator; the command is repeated the given number of times or until it fails. Numeric arguments prefixing an operand execute the operand the given number of times, effectively just moving the cursor. (Some versions of vi, such as that provided with AIX 5L, don't respond properly to numeric prefixes in front of some operands such as the / string search operand.)

Operators Description
d operand delete the operand into the (delete) buffer
p paste the contents of the (delete) buffer after the cursor
y operand yank the operand into the (delete) buffer
i operand inserts the operand (before current character)
a operand appends the operand (insert after current character)
r operand replaces current character with operand
s operand substitute the operand with typed-in text
c operand change the operand to typed-in text
! operand pass the operand to a (Unix) shell as standard input;
standard output replaces the operand.
Common Macros Description
I insert at beginning of line (same as ^i)
A append at end of line (same as $a)
D delete to end of line (same as d$)
C change to end of line (same as c$)
x delete one character (same as dl)
ZZ save and exit
:w filename save as filename without exiting
:q! quit immediately (without save)
Miscellaneous
R enter replace (overstrike) mode
o open line below current line
O open line above current line
" n n is 0-9: delete buffers
" x x is lowercase a-z: replace user buffer
" x x is uppercase A-Z: append to user buffer
. perform last change again
u undo last change
U undo all changes to current line
Operands Description
h j k l left, down, up, right; one character/line at a time
w b e next word, back word, end of word
W B E (same as above, but ignores punctuation)
/string search for string (use ? for reverse search)
n search for string again (see /, above)
% find matching ( ), { }, or [ ]
( ) beginning of current/previous sentence and beginning of next sentence
{ } beginning of current/previous paragraph (two adjacent newlines) and beginning of next paragraph (see also set paragraphs)
[[ ]] beginning of current/previous section and beginning of next section (mostly user-defined; see also set sections)
line G goto particular line number (defaults to end-of-file)
0 ^ $ move to column 0, move to first non-whitespace, move to end of line
f x forward to character x on same line (inclusive)
t x to character x on same line (not inclusive)
; last f or t again in the same direction
, last f or t again in the opposite direction
m x set mark x at current position
' x move to line containing mark x
` x move to exact position of mark x
'' move to line of last jump point
`` move to exact position of last jump point

Interesting examples of numeric prefixes would be 36i-*, 8i123456789-, and 20r_.


Ex (colon-mode) commands
In the following commands, file may be either a filename, or a shell command if prefixed with !. Filenames are globbed by the shell before vi uses them (shell wildcards are processed before the filenames are used). Address ranges may be used immediately after the colon in the commands below. Example address ranges are:

Range Description
1,$ From line 1 to the end of the file.
10,20 From line 10 to line 20, inclusive.
.,.+10 From the current line to current line + 10 (11 lines total).
'a,'d From the line containing mark a to the line containing mark d.
/from/,/to/ From the line containing "from" to the line containing "to", inclusive.
Commands which change the file being edited.
:e filename Change from the current file being edited to filename. "%" means current file, and "#" means alternate file.
Use :e # to edit the file most recently edited during the same session.
:n [filename(s)] Edits the next file from the command line. With optional list of filenames, changes command parameters and edits the first file in the list. Filenames are passed to the shell for wildcard substitution. Also consider command substitution:
:n `grep -l pattern *.c`
:args Lists the files from the command line (possibly as modified by :n, above).
:rew Restarts editing at the first filename from the command line.
Commands which modify the text buffer or disk file being edited.
:g/RE/cmd Globally search for regular expression and execute cmd for each line containing the pattern.
:s/RE/string/opt Search-and-replace; string is the replacement. Use opt to specify options c (confirm), g (globally on each line), and p (print after making change).
:w file Write the contents of the buffer to file. If file starts with an exclamation mark, the filename is interpreted as a shell command instead, and the buffer is piped into the command as stdin.
:r file Reads the contents of the file into the current buffer. If file starts with an exclamation mark, the filename is interpreted as a shell command instead, and the stdout of the command is read into the buffer.
These commands control the environment of the vi session.
:set opt Turns on boolean option opt.
:set noopt Turns off boolean option opt.
:set opt=val Sets option opt to val.
:set opt? Queries the setting of option opt.
Miscellaneous commands.
:abbr string phrase Creates abbreviation string for the phrase phrase. Abbreviations are replaced immediately as soon as recognized during text or command input. Use :unab string to remove an abbreviation.
:map key string Creates a mapping from key to string. This is different from an abbreviation in two ways: abbreviations are recognized as complete units only (for example, a word with surrounding whitespace) while mappings are based strictly on keystrokes, and mappings can apply to function keys by using a pound-sign followed by the function key number, i.e. #8 would map function key 8. If the terminal doesn't have an key, the mapping can be invoked by typing "#8" directly (doesn't work in the AIX 5L version of vi).
Here is an example of what my .exrc startup file in my home directory looks like:
set report=1 shiftwidth=4 tabstop=8 wrapmargin=10
set ai bf exrc magic nomesg modelines showmode nowrapscan
map! #1 `x=%; echo ${x\%/*}/
Some other command settings are ignorecase (ic), autowrite (aw), and showmatch (sm).

Pasted from

VIM advanced

1. Before doing anything to a document, type the following command followed by a carriage return: :set showmode

2. VI is CaSe SEnsItiVe!!! So make sure Caps Lock is OFF.


Starting and Ending VI

Starting VI

vi filename
Edits filename
vi -r filename
Edits last save version of filename after a crash
vi + n filename
Edits filename and places curser at line n
vi + filename
Edits filename and places curser on last line
vi +/string filename
Edits filename and places curser on first occurance of string
vi filename file2 ...
Edits filename, then edits file2 ... After the save, use :n
Ending VI

ZZ or :wq or :x
Saves and exits VI
:w
Saves current file but doesn't exit
:w!
Saves current file overriding normal checks but doesn't exit
:w file
Saves current as file but doesn't exit
:w! file
Saves to file overriding normal checks but doesn't exit
:n,mw file
Saves lines n through m to file
:n,mw >>file
Saves lines n through m to the end of file
:q
Quits VI and may prompt if you need to save
:q!
Quits VI and without saving
:e!
Edits file discarding any unsaved changes (starts over)
:we!
Saves and continues to edit current file


Status

:.=
Shows current line number
:=
Shows number of lines in file
Control-G
Shows filename, current line number, total lines in file, and % of file location
l
Displays tab (^l) backslash (\) backspace (^H) newline ($) bell (^G) formfeed (^L^) of current line


Modes

Vi has two modes insertion mode and command mode. The editor begins in command mode, where the cursor movement and text deletion and pasting occur. Insertion mode begins upon entering an insertion or change command. [ESC] returns the editor to command mode (where you can quit, for example by typing :q!). Most commands execute as soon as you type them except for "colon" commands which execute when you press the ruturn key.


Inserting Text

i
Insert before cursor
I
Insert before line
a
Append after cursor
A
Append after line
o
Open a new line after current line
O
Open a new line before current line
r
Replace one character
R
Replace many characters
CTRL-v char
While inserting, ignores special meaning of char (e.g., for inserting characters like ESC and CTRL) until ESC is used
:r file
Reads file and inserts it after current line
:nr file
Reads file and inserts it after line n
CTRL-i or TAB
While inserting, inserts one shift width

CTRL-h or Backspace
While inserting, deletes previous character
CTRL-w
While inserting, deletes previous word
CTRL-x
While inserting, deletes to start of inserted text
CTRL-v
Take the next character literally. (i.e. To insert a Control-H, type Control-v Control-h)
Things to do while in Insert Mode:


Motion

h
Move left
j
Move down
k
Move up
l
Move right
Arrow Keys
These do work, but they may be too slow on big files. Also may have unpredictable results when arrow keys are not mapped correctly in client.
w
Move to next word
W
Move to next blank delimited word
b
Move to the beginning of the word
B
Move to the beginning of blank delimted word
^
Moves to the first non-blank character in the current line
+ or
Moves to the first character in the next line
-
Moves to the first non-blank character in the previous line
e
Move to the end of the word
E
Move to the end of Blank delimited word
(
Move a sentance back
)
Move a sentance forward
{
Move a paragraph back
}
Move a paragraph forward
[[
Move a section back
]]
Move a section forward
0 or |
Move to the begining of the line
n|
Moves to the column n in the current line
$
Move to the end of the line
1G
Move to the first line of the file
G
Move to the last line of the file
nG
Move to nth line of the file
:n
Move to nth line of the file
fc
Move forward to c
Fc
Move back to c
H
Move to top of screen
nH
Moves to nth line from the top of the screen
M
Move to middle of screen
L
Move to botton of screen
nL
Moves to nth line from the bottom of the screen
Control-d
Move forward ½ screen
Control-f
Move forward one full screen
Control-u
Move backward ½ screen
Control-b
Move backward one full screen
CTRL-e
Moves screen up one line
CTRL-y
Moves screen down one line
CTRL-u
Moves screen up ½ page
CTRL-d
Moves screen down ½ page
CTRL-b
Moves screen up one page
CTRL-f
Moves screen down one page
CTRL-I
Redraws screen
z
z-carriage return makes the current line the top line on the page
nz
Makes the line n the top line on the page
z.
Makes the current line the middle line on the page
nz.
Makes the line n the middle line on the page
z-
Makes the current line the bottom line on the page
nz-
Makes the line n the bottom line on the page
%
Move to associated ( ), { }, [ ]


Deleting Text

Almost all deletion commands are performed by typing d followed by a motion. For example, dw deletes a word. A few other deletes are:
x
Delete character to the right of cursor
nx
Deletes n characters starting with current; omitting n deletes current character only
X
Delete character to the left of cursor
nX
Deletes previous n characters; omitting n deletes previous character only
D
Delete to the end of the line
d$
Deletes from the cursor to the end of the line
dd or :d
Delete current line
ndw
Deletes the next n words starting with current
ndb
Deletes the previous n words starting with current
ndd
Deletes n lines beginning with the current line
:n,md
Deletes lines n through m
dMotion_cmd
Deletes everything included in the Motion Command (e.g., dG would delete from current position to the end of the file, and d4 would delete to the end of the fourth sentence).
"np
Retrieves the last nth delete (last 9 deletes are kept in a buffer)
"1pu.u.
Scrolls through the delete buffer until the desired delete is retrieved (repeat u.)


Yanking Text

Like deletion, almost all yank commands are performed by typing y followed by a motion. For example, y$ yanks to the end of the line. Two other yank commands are:
yy
Yank the current line
:y
Yank the current line
nyy or nY
Places n lines in the buffer-copies
yMotion_cmd
Copies everything from the curser to the Motion Command (e.g., yG would copy from current position to the end of the file, and y4 would copy to the end of the fourth sentence)
"(a-z)nyy or "(a-z)ndd
Copies or cuts (deletes) n lines into a named buffer a through z; omitting n works on current line


Changing text

The change command is a deletion command that leaves the editor in insert mode. It is performed by typing c followed by a motion. For example cw changes a word. A few other change commands are:
C
Change to the end of the line
cc or S
Change the whole line until ESC is pressed
xp
Switches character at cursor with following character
stext
Substitutes text for the current character until ESC is used
cwtext
Changes current word to text until ESC is used
Ctext
Changes rest of the current line to text until ESC is used
cMotion_cmd
Changes to text from current position to Motion Command until ESC is used
<< or >>
Shifts the line left or right (respectively) by one shift width (a tab)
n<< or n>>
Shifts n lines left or right (respectively) by one shift width (a tab)
<Motion_cmd or >Motion_cmd
Use with Motion Command to shift multiple lines left or right


Putting text

p
Put after the position or after the line
P
Put before the poition or before the line
"(a-z)p or "(a-z)P
Pastes text from a named buffer a through z after or before the current line


Buffers

Named buffers may be specified before any deletion, change, yank or put command. The general prefix has the form "c where c is any lowercase character. for example, "adw deletes a word into buffer a. It may thereafter be put back into text with an appropriate "ap.


Markers

Named markers may be set on any line in a file. Any lower case letter may be a marker name. Markers may also be used as limits for ranges.
mc
Set marker c on this line
`c
Go to beginning of marker c line.
'c
Go to first non-blank character of marker c line.


Search for strings

/string
Search forward for string
?string
Search back for string
n
Search for next instance of string
N
Search for previous instance of string
%
Searches to beginning of balancing ( ) [ ] or { }
fc
Searches forward in current line to char
Fc
Searches backward in current line to char
tc
Searches forward in current line to character before char
Tchar
Searches backward in current line to character before char
?str
Finds in reverse for str
:set ic
Ignores case when searching
:set noic
Pays attention to case when searching
:n,ms/str1/str2/opt
Searches from n to m for str1; replaces str1 to str2; using opt-opt can be g for global change, c to confirm change (y to acknowledge, to suppress), and p to print changed lines
&
Repeats last :s command
:g/str/cmd
Runs cmd on all lines that contain str
:g/str1/s/str2/str3/
Finds the line containing str1, replaces str2 with str3
:v/str/cmd
Executes cmd on all lines that do not match str
,
Repeats, in reverse direction, last / or ? search command


Replace

The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).
:s/pattern/string/flags
Replace pattern with string according to flags.
g
Flag - Replace all occurences of pattern
c
Flag - Confirm replaces.
&
Repeat last :s command


Regular Expressions

. (dot)
Any single character except newline
*
zero or more occurances of any character
[...]
Any single character specified in the set
[^...]
Any single character not specified in the set
\<
Matches beginning of word
\>
Matches end of word
^
Anchor - beginning of the line
$
Anchor - end of line
\<
Anchor - begining of word
\>
Anchor - end of word
\(...\)
Grouping - usually used to group conditions
\n
Contents of nth grouping
\
Escapes the meaning of the next character (e.g., \$ allows you to search for $)
\\
Escapes the \ character

[A-Z]
The SET from Capital A to Capital Z
[a-z]
The SET from lowercase a to lowercase z
[0-9]
The SET from 0 to 9 (All numerals)
[./=+]
The SET containing . (dot), / (slash), =, and +
[-A-F]
The SET from Capital A to Capital F and the dash (dashes must be specified first)
[0-9 A-Z]
The SET containing all capital letters and digits and a space
[A-Z][a-zA-Z]
In the first position, the SET from Capital A to Capital Z
In the second character position, the SET containing all letters
[a-z]{m}
Look for m occurances of the SET from lowercase a to lowercase z
[a-z]{m,n}
Look for at least m occurances, but no more than n occurances of the SET from lowercase a to lowercase z
[...] - Set Examples

/Hello/
Matches if the line contains the value Hello
/^TEST$/
Matches if the line contains TEST by itself
/^[a-zA-Z]/
Matches if the line starts with any letter
/^[a-z].*/
Matches if the first character of the line is a-z and there is at least one more of any character following it
/2134$/
Matches if line ends with 2134
/\(21|35\)/
Matches is the line contains 21 or 35
Note the use of ( ) with the pipe symbol to specify the 'or' condition
/[0-9]*/
Matches if there are zero or more numbers in the line
/^[^#]/
Matches if the first character is not a # in the line
Notes:
1. Regular expressions are case sensitive
2. Regular expressions are to be used where pattern is specified

Regular Expression Examples


Counts

Nearly every command may be preceded by a number that specifies how many times it is to be performed. For example, 5dw will delete 5 words and 3fe will move the cursor forward to the 3rd occurence of the letter e. Even insertions may be repeated conveniently with this method, say to insert the same line 100 times.


Ranges

Ranges may precede most "colon" commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3-7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,$s/pattern/string/g to make a replacement from the current line to the end of the file.
:n,m
Range - Lines n-m
:.
Range - Current line
:$
Range - Last line
:'c
Range - Marker c
:%
Range - All lines in file
:g/pattern/
Range - All lines that contain pattern


Shell Functions

:! cmd
Executes shell command cmd; you can add these special characters to indicate:% name of current file# name of last file edited
!! cmd
Executes shell command cmd, places output in file starting at current line
:!!
Executes last shell command
:r! cmd
Reads and inserts output from cmd
:f file
Renames current file to file
:w !cmd
Sends currently edited file to cmd as standard input and execute cmd
:cd dir
Changes current working directory to dir
:sh
Starts a sub-shell (CTRL-d returns to editor)
:so file
Reads and executes commands in file (file is a shell script)
!Motion_cmd
Sends text from current position to Motion Command to shell command cmd
!}sort
Sorts from current position to end of paragraph and replaces text with sorted text


Files

:w file
Write to file
:r file
Read file in after line
:n
Go to next file
:p
Go to previous file
:e file
Edit file
!!program
Replace line with output from program


VI Settings

:set ai
Turns on auto indentation
:set all
Prints all options to the screen
:set ap
Prints line after d c J m :s t u commands
:set bf
Discards control characters from input
:set dir=tmp
Sets tmp to directory or buffer file
:set eb
Precedes error messages with a bell
:set ic
Ignores case when searching
:set lisp
Modifies brackets for Lisp compatibility.
:set list
Shows tabs (^l) and end of line ($)
:set magic
Allows pattern matching with special characters
:set mesg
Allows others to send messages
:set nooption
Turns off option
:set nu
Shows line numbers
:set opt
Speeds output; eliminates automatic RETURN
:set prompt
Prompts for command input with :
:set re
Simulates smart terminal on dumb terminal
:set report
Indicates largest size of changes reported on status line
:set ro
Changes file type to "read only"
:set scroll=n
set n lines for CTRL-d and z
:set sh=shell_path
set shell escape (default is /bin/sh) to shell_path
:set showmode
Indicates input or replace mode at bottom
:set sw=n
Sets shift width to n characters
:set term
Prints terminal type
:set terse
Shorten messages with terse
:set timeout
Eliminates one-second time limit for macros
:set tl=n
Sets significance of tags beyond n characters (0 means all)
:set ts=n
Sets tab stops to n for text input
:set wa
Inhibits normal checks before write commands
:set warn
Warns "no write since last change"
:set window=n
Sets number of lines in a text window to n
:set wm=n
Sets automatic wraparound n spaces from right margin.
Note: Options given are default. To change them, enter type :set option to turn them on or :set nooptioni to turn them off.To make them execute every time you open VI, create a file in your HOME directory called .exrc and type the options without the colon (:) preceding the option


Key Mapping

:map key cmd_seq
Defines key to run cmd_seq when pressed
:map
Displays all created macros on status line
:unmap key
Removes macro definition for key
:ab str string
When str is input, replaces it with string
:ab
Displays all abbreviations
:una str
Unabbreviates str
NOTE: Map allows you to define strings of VI commands. If you create a file called ".exrc" in your home directory, any map or set command you place inside this file will be executed every time you run VI. To imbed control characters like ESC in the macro, you need to precede them with CTRL-v. If you need to include quotes ("), precede them with a \ (backslash). Unused keys in vi are: K V g q v * = and the function keys.
Example (The actual VI commands are in blue): :map v /I CTRL-v ESC dwiYou CTRL-v ESC ESC
Description: When v is pressed, search for "I" (/I ESC), delete word (dw), and insert "You" (iYou ESC). CTRL-v allows ESC to be inserted


Other

~
Toggle upp and lower case
J
Join lines
nJ
Joins the next n lines together; omitting n joins the beginning of the next line to the end of the current line
.
Repeat last text-changing command
u
Undo last change (Note: u in combination with . can allow multiple levels of undo in some versions)
U
Undo all changes to line
;
Repeats last f F t or T search command


Quick HTTP to HTTPS - Apache2

There are several methods for redirecting your Apache-based website visitors who might type your servers URL using the plain (non-secure) HT...