You are on page 1of 107

The fundamental architecture of the GNU/Linux operating system

Short history of major Linux kernel releases

You've probably noticed that Linux as an operating system is referred to in some cases as "Linux" and in others as "GNU/Linux." The reason behind this is that Linux is the kernel of an operating system. The wide range of applications that make the operating system useful are the GNU software. For example, the windowing system, compiler, variety of shells, development tools, editors, utilities, and other applications exist outside of the kernel, many of which are GNU software. For this reason, many consider "GNU/Linux" a more appropriate name for the operating system, while "Linux" is appropriate when referring to just the kernel.

Linux directory commands


pwd - Display name of current directory The command >pwd is used to display the full path name of the current directory. cd - Switch to another directory To switch to another directory, the command cd is used. Examples What it does Cd Will place you in your home directory cd / Will move you to the root directory cd etc Will move you to the etc directory cd ../ Will move you back one directory

mkdir and rmdir - Create/Delete directories The command mkdir is used to create a new directory. The command rmdir or rm -r is used to delete a directory or directories
Examples mkdir mydirectory What it does Will create a new directory named 'mydirectory'

rmdir existingdirectory
rm -r existingdirectories

Will delete the existing directory named 'existingdirectory'


Will delete the existing directory named 'existingdirectories' and all directories and files below it.

ls - List the Contents of a directory The command ls is used to the contents of a directory
Options -l -R -a long listing list current directory and all other directories within current directory list hidden files What it does

-CF

list in column format and append '*' to executable files, '@' to symbolic linked files, '/' to directories
list in reverse alphabetically order

-r

-t

list more recent accessed files first

Examples Ls ls l ls R ls lt ls -lt /etc/rc*

What it does only list file/directory names in current directory list all file/directory information in current directory(long version) list all files in current directories and below list all files, sorted by most recent accessed first list files in the '/etc/ directory, only starting with 'rc' and sort results by most recent

Wildcards Wildcard characters are used to help find file or directory names
Options * ? [from-to ] What it does asterisk symbol is used to represent anycharacter(s) question mark is used to represent any single character Values entered within square brackets represent a range(from-to) for a single character Values entered within square brackets represent a range(from-to) to exclude for a single character

[!from-to ]

Examples a* *z a*m th?? [a-c]*

What it does all files starting with the letter 'a' all files where the last character is a 'z'

all files that start with the letter 'a' and end with 'm' all files that start with 'th' and are only four characters long
all files that start with 'a, b or c' all files that start with the letter 'x' and the second character contains 'A, B or C' all files except those that start with 'M, N or O'

x[A-C]*
[!M-O]*

File handling utilities


cp - Copy files To copy a file, the command cp is used Example:cp oldfile myfile - Will copy the existing file 'oldfile' to a new file 'myfile' mv - Rename files The command mv is used to rename a file Example: mv myfile yourfile - Will rename the file 'myfile' to 'yourfile'

rm - Delete files
Examples rm myfile What it does remove the file 'myfile'

rm -i abc*

prompt to remove each file in current directory starting with 'abc' remove all files in current directory starting with 'abc' automatically

rm abc*

wc - Count the number of lines or characters The command wc is used to count lines, words or characters in a file or piped results from another command.
Options What it does

-c
-w

Number of characters
Number of words

-l
filename Examples wc /etc/sendmail.cf ls etc wc -l file name(s) to use What it does Lists the number of lines, words and characters in the file 'sendmail.cf' Lists the number of files and directories in the directory 'etc'

file - Display Type-of-File Description Files can consist of several types. The command file is used to display a description for the type. Example: file a* will list all files in the current directory that start with the letter "a" and provide a description for the file type.

cat - concatenate files The command cat is a multi-purpose utility and is mostly used with TEXT files. Create a new file and optionally allow the manual entry of contents
cat >[filename] Example: cat >myfile will create a file named myfile and allow you to enter contents. Press Control-D to exit entry mode. WARNING: If "myfile" already existed, this command would replace the old file with the contents of the new file.

Combine text files


cat file1 file2 >newfile

- This will combine file1 and file2 into newfile.

Dissplay the contents of a file


cat myfile

Delete the contents of a file cat /dev/null >myfile

Linux file permissions


The basics of file ownership and permissions on Linux. Learn to understand who are the owners of a file or directory, how the file permissions work and how you can view them, and learn how to set basic file permissions yourself. Permissions and ownership - why? you must keep in mind Linux is designed to be a multi-user environment. In an environment with more than one users, it is crucial to have a secure system for deciding which files are yours and who can fiddle with them.

Understanding file ownership


Every file on your Linux system, including directories, is owned by a specific user and group. Therefore, file permissions are defined separately for users, groups, and others. User: the user who creates the file will become its owner. Group: The usergroup that owns the file. All users who belong into the group that owns the file will have the same access permissions to the file. Other: A user who isn't the owner of the file and doesn't belong in the same group the file does.

Understanding file permissions


There are three types of access permissions on Linux: read, write, and execute. These permissions are defined separately for the file's owner, group and all other users. Read permission. On a regular file, the read permission bit means the file can be opened and read. On a directory, the read permission means you can list the contents of the directory. Write permission. On a regular file, this means you can modify the file, and write new data to the file. In the case of a directory, the write permission means you can add, remove, and rename files in the directory. Execute permission. In the case of a regular file, this means you can execute the file as a program. On a directory, the execute permission allows you to access files in the directory and enter it

How to view file permissions


ls -l command This is what a long directory listing might look like: me@puter: /home/writers$ ls -l
drwxr-xr-x 3 nana writers 80 2005-09-20 21:37 dir -rw-r----- 1 nana writers 8187 2005-09-19 13:35 file -rwxr-xr-x 1 nana writers 10348 2005-07-17 20:31 otherfile

The first character can be any of these: d = directory - = regular file

The characters are pretty easy to remember. r = read permission w = write permission x = execute permission - = no permission

How to set file permissions - symbolic mode

You can set file permissions with the chmod command. Both the root user and the file's owner can set file permissions. chmod has two modes, symbolic and numeric.

Which user? u g o a What to do? + = add this permission remove this permission set exactly this permission user/owner group other All

Which permissions? r w x read write execute

Wipe out all the permissions but add read permission for everybody: $ chmod a=r testfile After the command, the file's permissions would be -r--r--r Add execute permissions for group: $ chmod g+x testfile Now, the file's permissions would be -r--r-xr- Add both write and execute permissions for the file's owner. Note how you can set more than one permission at the same time: $ chmod u+wx testfile After this, the file permissions will be -rwxr-xr- Remove the execute permission from both the file's owner and group. Note, again, how you can set them both at once: $ chmod ug-x testfile Now, the permissions are -rw-r--r--

How to set file permissions - numeric mode

The other mode in which chmod can be used is the numeric mode. In the numeric mode, the file permissions aren't represented by characters. Instead, they are represented by a three-digit octal number. 4 = read (r) 2 = write (w) 1 = execute (x) 0 = no permission (-) $ chmod 755 testfile $ chmod 640 testfile

Process utilities
The ps Command
The ps (i.e., process status) command is used to provide information about the currently running processes, including their process identification numbers (PIDs).

The basic syntax of ps is ps [options] $ ps PID TTY TIME 351 pts/1 00:00:00 3523514 pts/1 00:00:00

CMD bash ps

$ ps aux | less
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND heyne 691 0.0 2.4 19272 9576 pts/0 S 13:30 0:00 kdeinit: kded

$ps e | less -e displays all the system processes Use spacebar to move screen forward Hit b screen back q to quit $ps eo pid,%cpu,%mem,%stat(out put customization)

Who: know the users Displays the users currently logged in the system. luzar@ubuntu:~$ who root tty1 2009-07-06 22:06 luzar tty7 2009-07-06 19:17 (:0) luzar pts/0 2009-07-06 21:28 (:0.0)

Whoami: Show you the owner of this account luzar@ubuntu:~$ who am i Output: luzar pts/0 2009-07-06 22:39 (:0.0)

W: Tell you who is logging in and doing what! kucing@ubuntu-laptop:~$ w


09:15:10 up 43 min, 2 users, load average: 0.74, 0.38, 0.24 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT kucing tty7 :0 08:32 43:15m 57.73s 0.18s x-session-manager kucing pts/0 :0.0 08:48 0.00s 0.24s 0.00s w Options:

-h skip header -l long listing (default) -s short listing

Networking commands
FTP:file transfer protocol ftp abc.xyz.edu ftp> ls ftp> cd customers ftp> get image1.jpg ftp> put image2.jpg ftp> mget *.jpg ftp> mput *.jpg ftp> mdelete *.jpg ftp> quit

telnet :Communicate with another host To login into a another computer, the command telnet is used. You need at least 3 pieces of information to perform a telnet session: remote host IP address login name password Examples: telnet ahinc.com telnet 192.168.1.1

hostname: To display the host name, domain name or IP address of your machine $hostname i(ip address)

ping - Test network connection To test your network connection with another network device, the command ping is used $ping 192.168.1.1 Output: PING 192.168.1.1 (192.168.1.1): 56 data bytes 64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=0.2 ms 64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.1 ms 64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.1 ms

ifconfig - View network configuration ifconfig Displays... lo Link encap:Local Loopback inet addr:127.0.0.1 Bcast:127.255.255.255 Mask:255.0.0.0 UP BROADCAST LOOPBACK RUNNING MTU:3584 Metric:1 RX packets:292320 errors:0 dropped:0 overruns:0 TX packets:292320 errors:0 dropped:0 overruns:0 eth0 Link encap:10Mbps Ethernet HWaddr 00:60:94:57:D3:55 inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:7820768 errors:3465 dropped:0 overruns:0 TX packets:8643039 errors:0 dropped:0 overruns:0 Interrupt:14 Base address:0x5180

Disable an Interface $ifconfig eth0 down Enable an Interface $ ifconfig eth0 up Assign ip-address to an Interface Assign 192.168.2.2 as the IP address for the interface eth0. $ ifconfig eth0 192.168.2.2 Change Subnet mask of the interface eth0. $ ifconfig eth0 netmask 255.255.255.0 Change Broadcast address of the interface eth0. $ ifconfig eth0 broadcast 192.168.2.255 Assign ip-address, netmask and broadcast at the same time to interface eht0. $ ifconfig eth0 192.168.2.2 netmask 255.255.255.0 broadcast 192.168.2.255

Disk utilities
When you ever need to know how much space a file or directory is using on your disk, you should use du . du: Stands for disk usage,and displays how much disk space is used by file or directory. Syntax:
$du [options] [file/dir]

Options: -a -b -c -h -s

all files not just for directories it prints the size in bytes total disk space used by directory size in human redable format(k,m,g..) does not show the size of sub directories

examples
$du a venkatan 4 venkatan/ravi 4 venkatan/abhinav/kalyan 8 venkatan/abhinav 4 venkatan/foo 4 venkatan/file.text 24 venkatan

$du c venkatan 24 Venkatan 24 total


$du h venkatan 8.0k venkatan/abhinav 24k venkatan

df: Stands for disk free.used to find out empty disk space $df
Filesystem /dev/sda9 /dev/sdb1 1k-blocks used available use% 88244004 2382548 81378924 3% 964336 964304 32 100% mounted on / /media/phonecard

$df h
Filesystem /dev/sda9 /dev/sdb1 size 85G 99G used 2.3G 16G available 78G 84G use% 3% 16% mounted on / /media/disk

Mount: Mounting is done using mount command. $mount /dev/fd0 /mnt/floppy floppy device mount point $mount /dev/cdrom /mnt/cdrom The default mount points for different devices are configured in a file called /etc/fstab $umount /mnt/floppy (or) $umount /dev/fd0

filters
A filter is a program that reads a single input stream, transforms it in some way, and writes the result to a single output stream

Filter cat head tail wc sort more cmp diff tr sed uniq awk

What it does Copies input direct to output. Shows beginning of a file (default 10 lines). Shows end of a file (default 10 lines). Counts characters, words and lines. Sorts input lines. Displays contents of a file on screen. Comparision between two files byte by byte. Difference between two files. Translates or deletes specified character sets. Stream editor. Discards all but one of successive identical lines. Highly-programmable field-processing.

Tail command
Tail prints the last N number of lines from given input. By default, it prints last 10 lines of each given file. $ tail -5 flavours.txt
Debian Redhat Gentoo Fedora core

Head command
Head prints the first N number of data of the given input. By default, it prints first 10 lines of each given file. $ head -5 flavours.txt
Ubuntu Debian Redhat Gentoo Fedora core

$ head -5 file1 file2 ====> file1<==== first 5 lines from file1 ====> file2<==== first 5 lines from file1

sort command
The sort Command in linux is one of the most ignored(?) yet powerful command.Sort is used to sort data or records. if you use with other utils like ls it can give you wide varitety of data. Syntax: $sort [-options] fieldidentifier filename let's say the ls -l output of a directory is
-rw-r--r-- 1 nandam nandam 785280 2008-05-27 22:26 gdocs-1.0.4.oxt -rw-r--r-- 1 nandam nandam 4997184 2008-05-27 22:16 Sun_ODF_Template_Pack_en-US.oxt -rwxr-xr-x 1 nandam nandam 360756 2008-01-18 19:30 WriterTemplates.oxt -rwxr-xr-x 1 nandam nandam 48019 2008-01-18 19:30 WriterTools.oxt

$ls -l|sort -k 5 -k ---> instructs sort to sort records by column 5 in ascending order.
and now you will get the correct format as below
-rwxr-xr-x 1 nandam nandam 48019 2008-01-18 19:30 WriterTools.oxt -rwxr-xr-x 1 nandam nandam 360756 2008-01-18 19:30 WriterTemplates.oxt -rw-r--r-- 1 nandam nandam 785280 2008-05-27 22:26 gdocs-1.0.4.oxt -rw-r--r-- 1 nandam nandam 4997184 2008-05-27 22:16 Sun_ODF_Template_Pack_en-US.oxt

$sort -k 6,7 files.txt sort the data first by column 6 and then by column 7

More
The more command in Linux is helpful when dealing with a small xterm window, or if you want to easily read a file without using an editor to do so. More is a filter for paging through text one screenful at a time. 1. To View a File Using more erik@debian:~$ more fur.sh This will auto clear the screen and display the start of the file.

2. Pipe Output From cat Into more erik@debian:~$ cat data.txt | more

The main difference between more and less is that less allows backward and forward movement using the arrow keys, while more only uses the [Spacebar] and the [B] key for forward and backward navigation

cmp COMMAND: cmp linux command compares two files and tells you which line numbers are different. SYNTAX: cmp [options..] file1 file2

Compare two files: $cmp file1 file2 The above cmp command compares file1.php with file2.php and results as follows. file1.php file2.php differ: byte 35, line 3

Compare two files output differing bytes as characters: $cmp -c file1.php file2.php The above cmp command compares file1.php with file2.php and results as follows. file1.php file2.php differ: byte 35, line 3 is 151 i 15

diff
This command prints the differences between two files by performing the comparison lineby-line and by comparing first file with second file.
$diff file1 file2

File "one" Boo! Hey! Hi welcome

File "two"
Boo! Hey! Bye goodmorning

alex@tux ~/test $ diff one two 3c3 < Hi -->Bye 4c4 <welcome -->goodmorning

uniq
The uniq command reads the input file and compares adjacent lines. Any line that is the same as the one before it will be discarded. my.books file shown here: Atopic Dermatitis for Dummies Atopic Dermatitis for Dummies Chronic Rhinitis Unleashed Chronic Rhinitis Unleashed Chronic Rhinitis Unleashed Learn Nasal Endoscopy in 21 Days

$uniq my.books Atopic Dermatitis for Dummies Chronic Rhinitis Unleashed Learn Nasal Endoscopy in 21 Days

tr
This command is used for translating one character set to another. $tr [options] string1 string2 $Tr soatbge SOATBGE small opportunities are often the beginning of great enterprises. Ctrl+d

tutorial@fuzzy:~$echo my foot | tr o x My fxxt tutorial@fuzzy:~$ echo my foot | tr mo Tx Ty fxxt tutorial@fuzzy:~$ echo leet | tr let 137 1337 tutorial@fuzzy:~$ echo foo-foo | tr - _ Foo_foo
tutorial@fuzzy:~$ echo footbar | tr [:lower:] [:upper:]

FOOTBAR

cut

paste

Backup utilities
cpio: stands for copy in, copy out. cpio performs the following three operations. 1. Copying files to an archive 2. Extracting files from an archive 3. Passing files to another directory tree cpio takes the list of files from the standard input while creating an archive, and sends the output to the standard output.

1. Create *.cpio Archive File You can create a *.cpio archive that contains files and directories using cpio -ov $ cd objects $ ls file1.o file2.o file3.o $ ls | cpio -ov > /tmp/object.cpio

2. Extract *.cpio Archive File cpio extract: To extract a given *.cpio file, use cpio -iv as shown below. $ mkdir output $ cd output $ cpio -idv < /tmp/object.cpio

tar
c Create a new archive. t List the contents of an archive. x Extract the contents of an archive. f The archive file name is given on the command line (required whenever the tar output is going to a file) v Print verbose output (list file names as they are processed).

$tar cvf alldocs.tar *.doc $tar cvf panda.tar panda/ $tar cvf /dev/fd0 panda Archive the files in the panda directory to floppy disk(s). $tar cvf /dev/rmt0 panda Archive the files in the panda directory to the tape drive.

To list the contents of a tar file, use the t (type) flag in a command, like this: $tar tvf alldocs.tar List all files in alldocs.tar. To extract the contents of a tar file, use the x (extract) flag in a command, like this: $tar xvf panda.tar Extract files from panda.tar.

SED
Sed stands for stream editor. It reads the standard input ,processes it using a separate file called sed script and writes the result to the standard output. Sed script is file contains list of instructions to be applied to each line in the input file.

The sed command

sed command syntax

Sed script
It contains set of instructions to be applied to each line in the input file. If there is only one instruction it can be included at the command line. If there are more instructions ,they should be saved in a separate file with extension sed called sed script or sed program.

sed instruction format

address determines which lines in the input file are to be processed by the command(s)
if no address is specified, then the command is applied to each input line

address types:
Single-Line address Set-of-Lines address Range address Nested address

Example sed script


Demo.sed # comment one # comment two 3d 1,10s/friends/buddies

sed Operation

Frnd.txt greeting friend My friend Best friend always friend

$sed f myscript.sed frnd.txt Myscript.sed 1,3s/greeting/hello/ $s/always/forever/

How Does sed Work?


sed reads line of input
line of input is copied into a temporary buffer called pattern space editing commands are applied
subsequent commands are applied to line in the pattern space once finished, line is sent to output (unless n option was used)

line is removed from pattern space

sed reads next line of input, until end of file Note: input file is unchanged

Single-Line Address
Specifies only one line in the input file
special: dollar sign ($) denotes last line of input file

Examples: 6command applies command to line number 6 only $command applies command to last line
show only line 3 sed -n -e '3 p' input-file show only last line sed -n -e '$ p' input-file substitute endif with fi on line 10 sed -e '10 s/endif/fi/' input-file

Set-of-Lines Address
use regular expression to match lines
written between two slashes process only lines that match may match several lines lines may or may not be consecutives

Examples: /^A/command matches all lines that starts with A /^$/command applies command to last line
$

sed -e /key/ s/more/other/ input-file


80 CSCI 330 - The Unix System

$sed -n -e /r..t/ p input-file

Range Address
Defines a set of consecutive lines Format: start-addr,end-addr (inclusive) Examples:
10,50 10,/R.E/ /R.E./,10 /R.E./,/R.E/ line-number,line-number line-number,/RegExp/ /RegExp/,line-number /RegExp/,/RegExp/
81 CSCI 330 - The Unix System

Example: Range Address


% sed -n -e /^BEGIN$/,/^END$/p input-file
addr1 addr2

Print lines between BEGIN and END, inclusive


BEGIN Line 1 of input Line 2 of input Line3 of input END Line 4 of input Line 5 of input
82

These lines are printed

Nested Address
Nested address contained within another address Example: delete all blank lines between line 20 and 30
20,30{ /^$/d }

Address with !
address with an exclamation point (!): instruction will be applied to all lines that do not match the address Example: print lines that do not contain obsolete $sed -e /obsolete/!p input-file

sed commands

85

CSCI 330 - The Unix System

Line Number
line number command (=) writes the current line number before each matched/output line Examples:
$sed -e '/Two-thirds-time/=' tuition.data $sed -e =' inventory
86 CSCI 330 - The Unix System

modify commands

Substitute

87

CSCI 330 - The Unix System

Insert Command: i
adds one or more lines directly to the output before the address:
inserted text never appears in seds pattern space cannot be used with a range address; can only be used with the single-line and set-of-lines address types

Syntax:
[address] i\ text
88 CSCI 330 - The Unix System

Example: Insert Command (i)


% cat tuition.insert.sed 1 i\ Sed script to insert Tuition List Tuition List\ as report title before line 1 % cat tuition.data Part-time 1003.99 Input data Two-thirds-time 1506.49 Full-time 2012.29 % sed -f tuition.insert.sed tuition.data Tuition List Part-time Two-thirds-time Full-time 1003.99 1506.49 2012.29
89

Output after applying the insert command

CSCI 330 - The Unix System

Append Command: a
adds one or more lines directly to the output after the address:
Similar to the insert command (i), append cannot be used with a range address. Appended text does not appear in seds pattern space.

Syntax:
[address] a\ text
90 CSCI 330 - The Unix System

Example: Append Command (a)


% cat tuition.append.sed Sed script to append dashed line after a \ each input line -------------------------% cat tuition.data Part-time 1003.99 Input data Two-thirds-time 1506.49 Full-time 2012.29 % sed -f tuition.append.sed tuition.data Part-time 1003.99 -------------------------Two-thirds-time 1506.49 Output after applying -------------------------the append command Full-time 2012.29 -------------------------91 CSCI 330 - The Unix System

Change Command: c
replaces an entire matched line with new text accepts four address types:
single-line, set-of-line, range, and nested addresses.

Syntax:
address c\ text
92 CSCI 330 - The Unix System

Example: Change Command (c)


% cat tuition.change.sed Sed script to change 1 c\ tuition cost from 1003.99 to 1100.00 Part-time 1100.00 % cat tuition.data Part-time 1003.99 Input data Two-thirds-time 1506.49 Full-time 2012.29 % sed -f tuition.change.sed tuition.data Part-time 1100.00 Output after applying Two-thirds-time 1506.49 the change command Full-time 2012.29
93 CSCI 330 - The Unix System

Delete Command: d
deletes the entire pattern space
commands following the delete command are ignored since the deleted text is no longer in the pattern space

Syntax:
address d

94

CSCI 330 - The Unix System

Example: Delete Command (d)


Remove part-time data from tuition.data file
% cat tuition.data Part-time 1003.99 Two-thirds-time 1506.49 Full-time 2012.29
Input data

% sed e '/^Part-time/d' tuition.data applying delete Two-thirds-time 1506.49 command Full-time 2012.29
95 CSCI 330 - The Unix System

Output after

Substitute Command (s)


Syntax:
address s/search/replace/[flags]

replaces text selected by search string with replacement string search string can be regular expression flags:
global (g), i.e. replace all occurrences _ n is for specific occurence
96 CSCI 330 - The Unix System

sed i/o commands

98

CSCI 330 - The Unix System

Input (next) Command: n and N


Forces sed to read the next input line
Copies the contents of the pattern space to output Deletes the current line in the pattern space Refills it with the next input line Continue processing

N (uppercase) Command
adds the next input line to the current contents of the pattern space useful when applying patterns to two or more lines at the same time

99

CSCI 330 - The Unix System

cat test.dat first line second line line number 3 $sed '/second/{n; s/3/three/}' test.dat first line second line line number three

Output Command: p and P


Print Command (p)
copies the entire contents of the pattern space to output will print same line twice unless the option n is used

Print command: P
prints only the first line of the pattern space prints the contents of the pattern space up to and including a new line character any text following the first new line is not printed
101 CSCI 330 - The Unix System

cat test.dat first line second line line number three forth Line $sed -e '/second/{h; d;}' -e '$g' test.dat second line

Holding: H command
cat empl.dat
Albert Bronx:7187634623:Manhattan:m:56:32:cobol Alex Stachelin:7182347634:Brooklyn:m:60:60:unix ElizabethHarrington:7183214567:Brooklyn:f:42:40:cobol Fahd Main:7186794751:Queens:m:56:35:java Greg Norman:7182237890:Queens:m:45:0:java

$sed -e '/cobol/{H; d;}' -e '$g' empl.dat Alex Bronx:7187634623:Manhattan:m:56:32:cobol Elizabeth


Harrington:7183214567:Brooklyn:f:42:40:cobol

File commands
allows to read and write from/to file while processing standard input read: r command write: w command

110

CSCI 330 - The Unix System

Read File command


Syntax: r filename
queue the contents of filename to be read and inserted into the output stream at the end of the current cycle, or when the next input line is read

$sed '/cobol/r line.txt' test.dat

111

CSCI 330 - The Unix System

Write File command


Syntax: w filename
Write the pattern space to filename The filename will be created (or truncated) before the first input line is read

112

CSCI 330 - The Unix System

Writing: w command
$sed -n '/cobol/ w cobol_empl.dat' empl.datcat cobol_empl.dat

Albert Bronx:7187634623:Manhattan:m:56:32:cobol Elizabeth Harrington:7183214567:Brooklyn:f:42:40:cobol

Example: The quit (q) Command


Syntax: [addr]q
Quit (exit sed) when addr is encountered.

Example: Display the first 50 lines and quit


% sed -e 50q datafile
Same as: % sed -n -e 1,50p datafile % head -50 datafile

116

CSCI 330 - The Unix System

You might also like