header

Showing posts with label Unix. Show all posts
Showing posts with label Unix. Show all posts

vi editor sting search and replace

/string        search forward for string (end with Enter)
     ?string        search backward for string (end with Enter)
     n              repeat the last search (``next search'')
          :s/s1/s2       replace (``substitute'') (the first) s1 in this line by s2
     :lr/s/s1/s2/g  replace all instances of s1 in the line range lr by s2                     (lr is of form `a,b', where a and b are either explicit

pidof COMMAND:

pidof COMMAND:
pidof linux command is used to find the process ID of a running program.

SYNTAX:
The Syntax is
pidof [options..] program

OPTIONS:
-sSingle shot - this instructs the program to only return one pid.
-xScripts too - this causes the program to also return process id's of shells running the named scripts.
-oTells pidof to omit processes with that process id. The special pid %PPID can be used to name the parent process of the pidof program, in other words the calling shell or shell script.


EXAMPLE:
  1. To find a process id of a particular console:
    pidof -s console

    This command prints the process id of the console.

    3189

chown COMMAND:


chown COMMAND:
chown command is used to change the owner / user of the file or directory. This is an admin command, root user only can change the owner of a file or directory.

SYNTAX:
The Syntax is
chown [options] newowner filename/directoryname

OPTIONS:
-RChange the permission on files that are in the subdirectories of the directory that you are currently in.
-cChange the permission for each file.
-fPrevents chown from displaying error messages when it is unable to change the ownership of a file.


EXAMPLE:
  1. chown hiox test.txt

    The owner of the 'test.txt' file is root, Change to new user hiox.

  2. chown -R hiox test

    The owner of the 'test' directory is root, With -R option the files and subdirectories user also gets changed.

  3. chown -c hiox calc.txt

    Here change the owner for the specific 'calc.txt' file only

find COMMAND

find COMMAND:
find command finds one or more files assuming that you know their approximate filenames.

SYNTAX:
The Syntax is
find path [options]

OPTIONS:
-nameIt search for the given file, in the current directory or any other subdirectory.
-atime nTrue if the file was accessed n days ago. The access time of directories in path is changed by find itself.
-ctime nTrue if the file's status was changed n days ago.
-group gnameTrue if the file belongs to the group gname. If gname is numeric and does not appear in the /etc/group file, it is taken as a group ID.
-mtime nTrue if the file's data was modified n days ago.
-size n[c]True if the file is n blocks long (512 bytes per block). If n is followed by a c, the size is in bytes.


EXAMPLE:
  1. find -name 'cal.txt'

    The system would search for any file named 'cal.txt' in the current directory and any subdirectory.

  2. find / -name 'cal.txt'

    The system would search for any file named 'cal.txt' on the root and all subdirectories from the root.

  3. find -name '*' -size +1000k

    The system would search for any file in the list that is larger than 1000k.


ifconfig COMMAND

ifconfig COMMAND:
ifconfig command displays information about the network interfaces attached to the system and also used to configure the network interface.

SYNTAX:
The Syntax is
ifconfig [options]

OPTIONS:
-adispalys information about both active and inactive Interface
[interface-name]dispalys information about interface
[interface-name] upActivates the interface
[interface-name] downInactivates the interface
[interface-name] [IP Address] upAssigns IP address to the interface and activates it



EXAMPLE:
  1. To get information of active network-interfaces:
    ifconfig

    The sample output of above command:

    eth0
    Link encap:Ethernet HWaddr 00:14:85:9C:CC:55
    inet addr:192.168.0.12 Bcast:192.168.0.255 Mask:255.255.255.0
    inet6 addr: fe80::214:85ff:fe9c:cc55/64 Scope:Link
    UP LOOPBACK RUNNING MTU:16436 Metric:1
    RX packets:7856 errors:0 dropped:0 overruns:0 frame:0
    TX packets:7856 errors:0 dropped:0 overruns:0 carrier:0
    RX bytes:492016 (480.4 KiB) TX bytes:398 (398.0 b)
    Interrupt:201 Memory:e1000000-0
    lo
    Link encap:Local Loopback
    inet addr:127.0.0.1 Mask:255.0.0
    inet6 addr: ::1/128 Scope:Host
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:1455 errors:0 dropped:0 overruns:0 frame:0
    TX packets:5 errors:0 dropped:0 overruns:0 carrier:0
    RX bytes:1917382 (1.8 MiB) TX bytes:1917382 (1.8 MiB)
    In above output:
    Link encap:Ethernet-Specifies the type Interface
    HWaddr 00:14:85:9C:CC:55-Specifies the Hardware or MAC address
    inet addr:192.168.0.12-Specifies the IP address assigend to network-interface

  2. To Assign IP address to Network Interface[Ethernet Card]:
    ifconfig eth0 192.168.0.12 up
    The above command will Assign IP address 192.168.0.12 to Ethernet card with name eth0.
  3. To inactivate the Network Interface[Ethernet Card]:
    ifconfig eth0 down
    The above command inactivates the ethernet card.

Tar command

tar COMMAND:
tar command is used to create archive and extract the archive files.

SYNTAX:
The Syntax is
tar [options] [archive-file] [File or directory to be archived]

OPTIONS:

-cCreates Archive
-xExtract the archive
-fcreates archive with give filename
-tdisplays or lists files in archived file
-uarchives and adds to an existing archive file
-vDisplays Verbose Information
-AConcatenates the archive files



EXAMPLE:
  1. To archive a directory or file :
    tar -cvf backup.tar /etc

    This command creates a tarfile called backup.tar which is the archive of /etc directory.

    Where,
    backup.tar- Is a tar file created
    /etc- Is a directory archived

  2. To archive a directory or file and store it in a storage device:
    tar -cvf /dev/fd0 /home/user1/HGB

    This command will archive /etc directory and store it in floppy-disk.

    Where,
    /dev/fd0- Is a floppy-disk name where the archive is stored
    /home/user1/HGB- Is a directory archived

  3. To Extract the archive:
    tar -xvf backup.tar

    This command will extract the backup.tar file

  4. To List The File In An Archive:
    tar -tvf backup.tar

    The above command will display the files and directories that archived in backup.tar.


fgrep COMMAND

fgrep COMMAND:
fgrep command is used to search one or more files for lines that match the given string or word. fgrep is faster than grep search, but less flexible: it can only find fixed text, not regular expressions.

SYNTAX:
The Syntax is
fgrep [options] pattern [file]

OPTIONS:
-aDon't suppress output lines with binary data, treat as text.
-bPrint the byte offset of input file before each line of output.
-cPrint's the count of line matched.
-hPrint matched lines but not filenames.
-iIgnore changes in case; consider upper- and lower-case letters equivalent.
-nPrint line and line number.
-qPrints in quite mode, prints nothing.
-rRecursively read all files in directories and in subdirectories found.
-vPrints all the lines that do not match.
-VPrint Version.
-wMatch on whole word only.



EXAMPLE:
Lets assume that we have a file file1.txt and it has the following data.
ask your technical solution in our forum

  1. To search and print the lines containing forum :
    fgrep 'forum' file1.txt
    fgrep command prints the output as.
    ask your technical solution in our forum

Unix netstat COMMAND

netstat COMMAND:
nestat command displays statistics information and current state of network connections, protocol, ports/ sockets and devices.

SYNTAX:
The Syntax is
netstat [options]

OPTIONS:
-sdispalys statics information about protocols.
-idispalys statistics information about the network interface.
-rdiplays routing table.
-cdisplays statistics information and updates every second.
-ldisplays information about all sockets that are in listening state.
-adisplays information about all sockets that are in listening and non-listening state.
-pdisplays information about sockets with ProcessName and PID.



EXAMPLE:
  1. To get statistics of network connections:
    netstat
    The sample output of above command:
    Active Internet connections (w/o servers)
    ProtoRecv-QSend-QLocal AddressForeign AddressState
    tcp00vhost:32803LocalHost:smtpTIME_WAIT
    tcp00vhost:32803google.com:httpESTABLISHED

    Where,
    Proto-Specifies the Protocol used for connection.
    Recv-Q-Specifies the Number of Bytes which are not recevied.
    Send-Q-Specifies the Number of Bytes not send to destination.
    Local Address-Specifies the local or source address and port.
    Foreign Address-Specifies the destination address and port.
    State-Specifies the current state of conection to the socket.
    • ESTABLISHED - Connection is Established.
    • TIME_WAIT - Waiting to receive packets.
    • LISTEN - Listening to establish connection.
  2. To Get Statistics of Protocols:
    netstat -s
    The Sample output of above command:
    IP:
    5193 incoming packets delivered
    4813 requests sent out
    Tcp:
    4033 segments received
    4813 segments send out
    Icmp:
    41 ICMP messages received
    178 ICMP messages sent
  3. To Get statistics of Network Interface:
    netstat -i
    The sample output of above command:

    Kernel Interface table
    IfaceMTUMetRX-OKRX-ERRTX-OKTX-ERRFlg
    eth0150001308013450BMRU
    This is the statistics information of Ethernet Card[eth0

awk COMMAND

awk COMMAND:
awk command is used to manipulate the text.This command checks each line of a file, looking for patterns that match those given on the command line.

SYNTAX:
The Syntax is
awk '{pattern + action}' {filenames}

OPTIONS:
-W versionDisplay version information and exit.
-FPrint help message and exit.



EXAMPLE:
Lets create a file file1.txt and let it have the following data:
Data in file1.txt
14 15 16
15 15 11
5 56 6
5 25 1
  1. To print the second column data in file1.txt
    awk '{print $2}' file1.txt

    This command will manipulate and print second column of text file (file1.txt). The output will look like

    15
    15
    56
    25

  2. To multiply the column-1 and column-2 and redirect the output to file2.txt:
    awk '{print $1,$2,$1*$2}' file1.txt > file2.txt
    Command Explanation:
    $1: Prints 1st column
    $2: Prints 2ndcolumn
    $1*$2: Prints Result of $1 x $2
    file1.txt: input file
    >: redirection symbol
    file2.txt: output file

    The above command will redirect the output to file2.txt and it will look like,
    14 15 210
    15 15 225
    5 56 280
    5 25 12

Unix commands in 10-minutes


Directories:

File and directory paths in UNIX use the forward slash "/"
to separate directory names in a path.
examples:
/ "root" directory
/usr directory usr (sub-directory of / "root" directory)
/usr/STRIM100 STRIM100 is a subdirectory of /usr

Moving around the file system:

pwd Show the "present working directory", or current directory.
cd Change current directory to your HOME directory.
cd /usr/STRIM100 Change current directory to /usr/STRIM100.
cd INIT Change current directory to INIT which is a sub-directory of the current
directory.
cd .. Change current directory to the parent directory of the current directory.
cd $STRMWORK Change current directory to the directory defined by the environment
variable 'STRMWORK'.
cd ~bob Change the current directory to the user bob's home directory (if you have permission).

Listing directory contents:

ls list a directory
ls -l list a directory in long ( detailed ) format
for example:
$ ls -l
drwxr-xr-x 4 cliff user 1024 Jun 18 09:40 WAITRON_EARNINGS
-rw-r--r-- 1 cliff user 767392 Jun 6 14:28 scanlib.tar.gz
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^

owner group size date time name
number of links to file or directory contents
permissions for world
permissions for members of group
permissions for owner of file: r = read, w = write, x = execute -=no permission
type of file: - = normal file, d=directory, l = symbolic link, and others...
ls -a List the current directory including hidden files. Hidden files start
with "."
ls -ld * List all the file and directory names in the current directory using
long format. Without the "d" option, ls would list the contents
of any sub-directory of the current. With the "d" option, ls
just lists them like regular files.

Changing file permissions and attributes

chmod 755 file Changes the permissions of file to be rwx for the owner, and rx for
the group and the world. (7 = rwx = 111 binary. 5 = r-x = 101 binary)
chgrp user file Makes file belong to the group user.
chown cliff file Makes cliff the owner of file.
chown -R cliff dir Makes cliff the owner of dir and everything in its directory tree.
You must be the owner of the file/directory or be root before you can do any of these things.

Moving, renaming, and copying files:

cp file1 file2 copy a file
mv file1 newname move or rename a file
mv file1 ~/AAA/ move file1 into sub-directory AAA in your home directory.
rm file1 [file2 ...] remove or delete a file
rm -r dir1 [dir2...] recursivly remove a directory and its contents BE CAREFUL!
mkdir dir1 [dir2...] create directories
mkdir -p dirpath create the directory dirpath, including all implied directories in the path.
rmdir dir1 [dir2...] remove an empty directory

Viewing and editing files:

cat filename Dump a file to the screen in ascii.
more filename Progressively dump a file to the screen: ENTER = one line down
SPACEBAR = page down q=quit
less filename Like more, but you can use Page-Up too. Not on all systems.
vi filename Edit a file using the vi editor. All UNIX systems will have vi in some form.
emacs filename Edit a file using the emacs editor. Not all systems will have emacs.
head filename Show the first few lines of a file.
head -n filename Show the first n lines of a file.
tail filename Show the last few lines of a file.
tail -n filename Show the last n lines of a file.

Shells

The behavior of the command line interface will differ slightly depending
on the shell program that is being used.
Depending on the shell used, some extra behaviors can be quite nifty.
You can find out what shell you are using by the command:
echo $SHELL
Of course you can create a file with a list of shell commands and execute it like
a program to perform a task. This is called a shell script. This is in fact the
primary purpose of most shells, not the interactive command line behavior.

Environment variables

You can teach your shell to remember things for later using environment variables.
For example under the bash shell:
export CASROOT=/usr/local/CAS3.0 Defines the variable CASROOT with the value
/usr/local/CAS3.0.
export LD_LIBRARY_PATH=$CASROOT/Linux/lib Defines the variable LD_LIBRARY_PATH with
the value of CASROOT with /Linux/lib appended,
or /usr/local/CAS3.0/Linux/lib
By prefixing $ to the variable name, you can evaluate it in any command:
cd $CASROOT Changes your present working directory to the value of CASROOT
echo $CASROOT Prints out the value of CASROOT, or /usr/local/CAS3.0
printenv CASROOT Does the same thing in bash and some other shells.

Interactive History

A feature of bash and tcsh (and sometimes others) you can use
the up-arrow keys to access your previous commands, edit
them, and re-execute them.

Filename Completion

A feature of bash and tcsh (and possibly others) you can use the
TAB key to complete a partially typed filename. For example if you
have a file called constantine-monks-and-willy-wonka.txt in your
directory and want to edit it you can type 'vi const', hit the TAB key,
and the shell will fill in the rest of the name for you (provided the
completion is unique).

Bash is the way cool shell.

Bash will even complete the name of commands and environment variables.
And if there are multiple completions, if you hit TAB twice bash will show
you all the completions. Bash is the default user shell for most Linux systems.

Redirection:

grep string filename > newfile Redirects the output of the above grep
command to a file 'newfile'.
grep string filename >> existfile Appends the output of the grep command
to the end of 'existfile'.
The redirection directives, > and >> can be used on the output of most commands
to direct their output to a file.

Pipes:

The pipe symbol "" is used to direct the output of one command to the input
of another.
For example:
ls -l more This commands takes the output of the long format directory list command
"ls -l" and pipes it through the more command (also known as a filter).
In this case a very long list of files can be viewed a page at a time.
du -sc * sort -n tail
The command "du -sc" lists the sizes of all files and directories in the
current working directory. That is piped through "sort -n" which orders the
output from smallest to largest size. Finally, that output is piped through "tail"
which displays only the last few (which just happen to be the largest) results.

Command Substitution

You can use the output of one command as an input to another command in another way
called command substitution. Command substitution is invoked when by enclosing the
substituted command in backwards single quotes. For example:
cat `find . -name aaa.txt`
which will cat ( dump to the screen ) all the files named aaa.txt that exist in the current
directory or in any subdirectory tree.

Searching for strings in files: The grep command

grep string filename prints all the lines in a file that contain the string

Searching for files : The find command

find search_path -name filename
find . -name aaa.txt Finds all the files named aaa.txt in the current directory or
any subdirectory tree.
find / -name vimrc Find all the files named 'vimrc' anywhere on the system.
find /usr/local/games -name "*xpilot*"
Find all files whose names contain the string 'xpilot' which
exist within the '/usr/local/games' directory tree.

Reading and writing tapes, backups, and archives: The tar command

The tar command stands for "tape archive". It is the "standard" way to read
and write archives (collections of files and whole directory trees).
Often you will find archives of stuff with names like stuff.tar, or stuff.tar.gz. This
is stuff in a tar archive, and stuff in a tar archive which has been compressed using the
gzip compression program respectivly.
Chances are that if someone gives you a tape written on a UNIX system, it will be in tar format,
and you will use tar (and your tape drive) to read it.
Likewise, if you want to write a tape to give to someone else, you should probably use
tar as well.
Tar examples:
tar xv Extracts (x) files from the default tape drive while listing (v = verbose)
the file names to the screen.
tar tv Lists the files from the default tape device without extracting them.
tar cv file1 file2
Write files 'file1' and 'file2' to the default tape device.
tar cvf archive.tar file1 [file2...]
Create a tar archive as a file "archive.tar" containing file1,
file2...etc.
tar xvf archive.tar extract from the archive file
tar cvfz archive.tar.gz dname
Create a gzip compressed tar archive containing everything in the directory
'dname'. This does not work with all versions of tar.
tar xvfz archive.tar.gz
Extract a gzip compressed tar archive. Does not work with all versions of tar.
tar cvfI archive.tar.bz2 dname
Create a bz2 compressed tar archive. Does not work with all versions of tar

File compression: compress, gzip, and bzip2

The standard UNIX compression commands are compress and uncompress. Compressed files have
a suffix .Z added to their name. For example:
compress part.igs Creates a compressed file part.igs.Z
uncompress part.igs Uncompresseis part.igs from the compressed file part.igs.Z.
Note the .Z is not required.
Another common compression utility is gzip (and gunzip). These are the GNU compress and
uncompress utilities. gzip usually gives better compression than standard compress,
but may not be installed on all systems. The suffix for gzipped files is .gz
gzip part.igs Creates a compressed file part.igs.gz
gunzip part.igs Extracts the original file from part.igs.gz
The bzip2 utility has (in general) even better compression than gzip, but at the cost of longer
times to compress and uncompress the files. It is not as common a utility as gzip, but is
becoming more generally available.
bzip2 part.igs Create a compressed Iges file part.igs.bz2
bunzip2 part.igs.bz2 Uncompress the compressed iges file.

Looking for help: The man and apropos
commands
Most of the commands have a manual page which give sometimes useful, often more or less
detailed, sometimes cryptic and unfathomable discriptions of their usage. Some say they
are called man pages because they are only for real men.
Example:
man ls Shows the manual page for the ls command
You can search through the man pages using apropos
Example:
apropos build Shows a list of all the man pages whose discriptions contain the word "build"
Do a man apropos for detailed help on apropos.

Basics of the vi editor

Opening a file
vi filename
Creating text
Edit modes: These keys enter editing modes and type in the text
of your document.
i Insert before current cursor position
I Insert at beginning of current line
a Insert (append) after current cursor position
A Append to end of line
r Replace 1 character
R Replace mode
Terminate insertion or overwrite mode
Deletion of text
x Delete single character
dd Delete current line and put in buffer
ndd Delete n lines (n is a number) and put them in buffer
J Attaches the next line to the end of the current line (deletes carriage return).
Oops
u Undo last command
cut and paste
yy Yank current line into buffer
nyy Yank n lines into buffer
p Put the contents of the buffer after the current line
P Put the contents of the buffer before the current line
cursor positioning
^d Page down
^u Page up
:n Position cursor at line n
:$ Position cursor at end of file
^g Display current line number
h,j,k,l Left,Down,Up, and Right respectivly. Your arrow keys should also work if
if your keyboard mappings are anywhere near sane.
string substitution
:n1,n2:s/string1/string2/[g] Substitute string2 for string1 on lines
n1 to n2. If g is included (meaning global),
all instances of string1 on each line
are substituted. If g is not included,
only the first instance per matching line is
substituted.
^ matches start of line
. matches any single character
$ matches end of line
These and other "special characters" (like the forward slash) can be "escaped" with \
i.e to match the string "/usr/STRIM100/SOFT" say "\/usr\/STRIM100\/SOFT"
Examples:
:1,$:s/dog/cat/g Substitute 'cat' for 'dog', every instance
for the entire file - lines 1 to $ (end of file)
:23,25:/frog/bird/ Substitute 'bird' for 'frog' on lines
23 through 25. Only the first instance
on each line is substituted.
Saving and quitting and other "ex" commands
These commands are all prefixed by pressing colon (:) and then entered in the lower
left corner of the window. They are called "ex" commands because they are commands
of the ex text editor - the precursor line editor to the screen editor
vi. You cannot enter an "ex" command when you are in an edit mode (typing text onto the screen)
Press to exit from an editing mode.
:w Write the current file.
:w new.file Write the file to the name 'new.file'.
:w! existing.file Overwrite an existing file with the file currently being edited.
:wq Write the file and quit.
:q Quit.
:q! Quit with no changes.
:e filename Open the file 'filename' for editing.
:set number Turns on line numbering
:set nonumber Turns off line numbering