linux set date
TRANSCRIPT
-
7/31/2019 Linux Set Date
1/101
-
7/31/2019 Linux Set Date
2/101
So we see that df gives some valuable information on the file systems,their mount points, their memory usage etc.
1. Display Information of all the File Systems
If the disk usage of all the file systems is required then use -a option:
$ df -aFilesystem 1K-blocks UsedAvailable Use% Mounted on/dev/sda1 132239776 6210892119311496 5% /proc 0 00 - /procsysfs 0 00 - /sysdevpts 0 00 - /dev/ptstmpfs 4021876 04021876 0% /dev/shmnone 0 0
0 - /proc/sys/fs/binfmt_misc/dev/sdb2 30969600 11774029278696 1% /home/oracle/dev/sdc1 576310180 71232546964104 1% /home/data
So we see that in the output, details of all the file systems and theirmemory usage is there.
2. Specify the Memory Block Size
If you see the output in point 1 above, the second column gives thememory of file system in memory blocks of 1k. df command providesan option through which we can change the size of memory block inthe output. Use option -B for this:
$ df -B 100
-
7/31/2019 Linux Set Date
3/101
Filesystem 100B-blocks UsedAvailable Use% Mounted on/dev/sda1 1354135307 635995351221749720 5% /
tmpfs 41184011 041184011 0% /dev/shm/dev/sdb2 317128704 1205658299813848 1% /home/oracle/dev/sdc1 5901416244 7294165600912425 1% /home/data
So you see that we specified a block size of 100 and in the output
(second column) block size of 100 is displayed.
3. Print Human Readable Sizes
We are used to reading the memory in terms of gigabytes, megabytes,etc as its easy to read and remember. df command also provides anoption -h to print the memory statistics in human readable format.
Option -h stands for human readable format. As shown in the output
below, G is used for gigabytes and M is used for megabytes.
$ df -hFilesystem Size Used Avail Use%Mounted on/dev/sda1 127G 6.0G 114G 5% /tmpfs 3.9G 0 3.9G 0%/dev/shm
/dev/sdb2 30G 115M 28G 1%/home/oracle/dev/sdc1 550G 70M 522G 1%/home/data
4. Display Grand Total in the Output
Till now we have seen that only disk usage statistics of individual filesystems is produced. If we want to display a grand total of every
column then we can use the total flag. Here is an example:
-
7/31/2019 Linux Set Date
4/101
$ df -h --totalFilesystem Size Used Avail Use%Mounted on/dev/sda1 127G 6.0G 114G 5% /
tmpfs 3.9G 0 3.9G 0%/dev/shm/dev/sdb2 30G 115M 28G 1%/home/oracle/dev/sdc1 550G 70M 522G 1%/home/datatotal 710G 6.2G 668G 1%
So we see that a new row total at the end of the output was produced.
5. List Inodes (Instead of Block Usage)
Till now we have seen that df prints the second column as totalmemory blocks. If information in terms of inode is desired then dfprovides an option -i for this.
$ df -i
Filesystem Inodes IUsed IFreeIUse% Mounted on/dev/sda1 8396800 65397 83314031% /tmpfs 1005469 1 10054681% /dev/shm/dev/sdb2 1966560 2517 19640431% /home/oracle
/dev/sdc1 36593664 11 365936531% /home/data
So we see that information in terms of inodes is displayed.
6. Print File System Type
If you wish to print the type of file system in the output, use option -T.
$ df -T
-
7/31/2019 Linux Set Date
5/101
Filesystem Type 1K-blocks UsedAvailable Use% Mounted on/dev/sda1 ext4 132239776 6210892119311496 5% /
tmpfs tmpfs 4021876 04021876 0% /dev/shm/dev/sdb2 ext2 30969600 11774029278696 1% /home/oracle/dev/sdc1 ext2 576310180 71232546964104 1% /home/data
In the above output, we can see all the file systems along with their
type is displayed. Apart from using df -T to identify file system, thereare 4 other methods to identify the file system types.
7. Include/Exclude Certain File System Type
You can also display file systems that belongs to certain type. Forexample, the following command displays only ext2 file systems.types.
$ df -t ext2Filesystem 1K-blocks UsedAvailable Use% Mounted on/dev/sdb2 30969600 11774029278696 1% /home/oracle/dev/sdc1 576310180 71232546964104 1% /home/data
Mount Command
The syntax is as follows:
mount /dev/XYZN /mount/point
WARNING! The mount commands require root userprivilege or the corresponding fine-grained privilege,
http://www.thegeekstuff.com/2011/04/identify-file-system-type/http://www.thegeekstuff.com/2011/04/identify-file-system-type/ -
7/31/2019 Linux Set Date
6/101
unless the file system is defined as "user mountable" in
the /etc/fstab file.
Examples
Mount /dev/sda5 (Linux partition) in /data directory:
mkdir /datamount /dev/sda5 /datadf -Hls /datacd/data
Mount /dev/aacd0s1g (FreeBSD UNIX partition) in /salesdatadirectory:
mkdir /salesdatadf -H
mount /dev/aacd0s1g /salesdatals /salesdatacd/salesdata
Mount /dev/dsk/c1t4d0s0 under Solaris UNIX at /data2, enter:
mkdir /data2mount /dev/dsk/c1t4d0s0 /data2
To remove mount point run:
umount /salesdata
To mount all file systems listed in /etc/fstab, enter:
mount -a
Further readings:
man mount
du
-
7/31/2019 Linux Set Date
7/101
You need use the command line utility called du to displays the filesystem block usage. In this example find out /tmp dir disk usagestatistics (open the terminal and type the following command):$ du /tmp
Sample outputs:
4 /tmp/vmware-root8 /tmp/pulse-xc7xdoM9vB2K4 /tmp/.X11-unix4 /tmp/keyring-7qXGnQ4 /tmp/.exchange-vivek4 /tmp/.winbindd
8 /tmp/plugtmp4 /tmp/virtual-vivek.C81Sd04 /tmp/VMwareDnD4 /tmp/ssh-mhNeIv19614 /tmp/.ICE-unix8 /tmp/orbit-vivek4 /tmp/.esd-100031644 /tmp
The -h option provides "Human-readable" outpu i.e. you will see it inByte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte:$ du -h /tmp
Sample outputs:
4.0K /tmp/vmware-root8.0K /tmp/pulse-xc7xdoM9vB2K4.0K /tmp/.X11-unix
4.0K /tmp/keyring-7qXGnQ4.0K /tmp/.exchange-vivek4.0K /tmp/.winbindd8.0K /tmp/plugtmp4.0K /tmp/virtual-vivek.C81Sd04.0K /tmp/VMwareDnD4.0K /tmp/ssh-mhNeIv19614.0K /tmp/.ICE-unix
8.0K /tmp/orbit-vivek4.0K /tmp/.esd-1000
http://www.cyberciti.biz/tips/linux-unix-du-command-examples.htmlhttp://www.cyberciti.biz/tips/linux-unix-du-command-examples.html -
7/31/2019 Linux Set Date
8/101
33M /tmp
df: Display Free Disk Space
To show statistics about the amount of free disk space on the specifiedfile system or on the file system of which file is a part use the dfcommand as follows:$ df$ df -h
Sample outputs:
Filesystem Size Used Avail CapacityMounted on/dev/wd0a 938M 43.0M 848M 5% //dev/wd0e 817M 2.0K 776M0% /home/dev/wd0d 2.9G 573M 2.2G20% /usr
GUI Tools: Disk Usage Analyzer (Gnome Version)
Disk Usage Analyzer is a graphical, menu-driven application to analyzedisk usage in any UNIX / Linux / BSD Gnome desktop environment.Disk Usage Analyzer can easily scan either the whole filesystem tree,or a specific user-requested directory branch (local or remote). To startthis tool visit Gnome menu click on > Applications > Accessories >Select the Disk Usage AnalyzerAlternatively, you can start Disk Usage Analyzer from a terminalwindow, just type:
baobabbaobab /path/to/dirbaobab /home/vivek/mp3/
Sample outputs:
-
7/31/2019 Linux Set Date
9/101
Fig.01: GUI command to check UNIX / Linux / BSD disk space
Now, you can:
Start a full filesystem scan Select a specific local directory branch to scan Select a remote server and folder to scan etc
To start a full filesystem scan select Analyzer > Scan Filesystem fromthe menu, or press on the Scan Filesystem toolbar button. Disk UsageAnalyzer will display sizes in the directory tree as allocated space. This
means that the displayed sizes refer to the actual disk usage and not tothe apparent directory size. If you want to view the apparent file size,uncheck View > Allocated Space .
http://www.cyberciti.biz/faq/unix-disk-usage-command-examples/unix-disk-usage-analyzer/ -
7/31/2019 Linux Set Date
10/101
-
7/31/2019 Linux Set Date
11/101
With that command, the -h option of the du command means "human
readable" (as in "show me MB and GB"), and the -s means "only
show summary information". It's important to note that this commandruns in real time, so for very large directories, it can be slow to returnyour results.
Show the size of only specified directories
Also, in that du command example, I knew that my current directoryjust contained the subdirectories shown, so I just issued that ducommand followed by the "*" wildcard character. If, in a morecomplicated world, I just wanted to see the size of a few subdirectories
in a directory that contained many more subdirectories, I could justspecify the directories of interest, like this:
$ du -hs Dir1 Dir2 Dir3
Linux du command output without the summary flag
As you can see, if I take the -s option off my du command I do indeed
get much lengthier output, like this:
$ du -h *
60K Burn-an-ISO376K BurnFolders/BurnFolders188K BurnFolders/images296K BurnFolders/images-orig1.2M BurnFolders
568K CreateAPodcast-1/CreateAPodcast1.1M CreateAPodcast-1/images/Original2.4M CreateAPodcast-1/images628K CreateAPodcast-1/L2HBackups28K CreateAPodcast-1/OldCSSFiles4.3M CreateAPodcast-1868K CreateAPodcast-2/CreateAPodcast740K CreateAPodcast-2/images
2.1M CreateAPodcast-23.8M CreateAPodcast-3/CreateAPodcast
-
7/31/2019 Linux Set Date
12/101
1.8M CreateAPodcast-3/images/bg-track720K CreateAPodcast-3/images/copying668K CreateAPodcast-3/images/external-track688K CreateAPodcast-3/images/joining
828K CreateAPodcast-3/images/new-track1.1M CreateAPodcast-3/images/splitting6.0M CreateAPodcast-3/images1.2M CreateAPodcast-3/images-orig/bg-track468K CreateAPodcast-3/images-orig/copying444K CreateAPodcast-3/images-orig/external-track464K CreateAPodcast-3/images-orig/joining
556K CreateAPodcast-3/images-orig/new-track768K CreateAPodcast-3/images-orig/splitting3.9M CreateAPodcast-3/images-orig16M CreateAPodcast-3200K Java-Mac-Jar-Bundler/images676K Java-Mac-Jar-Bundler/images copy808K Java-Mac-Jar-Bundler/images-old328K Java-Mac-Jar-Bundler/java-on-mac
2.5M Java-Mac-Jar-Bundler308K Java-on-Mac/images448K Java-on-Mac/java-on-mac1.3M Java-on-Mac
I'll guess that at least 95% of the time I use the -s option, because I'm
usually tracking down large directories, or I want to see the directorysize before I create an archive.
Chmod command Examples in UNIX and Linux
Now let's see some practical and frequently used example ofchmodcommand in UNIX
-
7/31/2019 Linux Set Date
13/101
chmod command Example 1: making read only file in Unix
In this example of chmod command in UNIX we will see how tomake a file read only by only providing read access to owner.
You can also give read access to group and others and keepwrite access for owner which we will see in subsequentexamples.
example@localhost~/testls-lrtstock_trading_systems-rwxrwxrwx 1 example Domain Users 0 Jul 1511:42 stock_trading_systems*
Here file stock_trading_systems has read, write and executepermission -rwxrwxrwx" for all
example@localhost~/testchmod400stock_trading_systems
400 means 100 000 000 means r-- --- --- i.e.read only for owner
example@localhost~/testls-lrtstock_trading_systems-r-------- 1 example Domain Users 0 Jul 1511:42 stock_trading_systems
Now file is read only and only owner can read it -r--------"
chmod command Example 2: change permissions only foruser, group or others.
In this example of chmod command we will see how to changefile permissions on user, group and others level. You can easily
-
7/31/2019 Linux Set Date
14/101
modify file permission for any of these classes. If you are usingtext format than u is user , o is other and g is group also ris read , w is write and x is execute. + means addingpermission and -is removing permission.
example@localhost~/testls-lrt chmod_examples-r-------- 1 example Domain Users 0 Jul 1511:42 chmod_examples
example@localhost~/testchmodu+wchmod_examples
example@localhost~/testls-lrt chmod_examples-rw------- 1 example Domain Users 0 Jul 1511:42 chmod_examples
Now lets change file permissions only for group by using chmodcommand
example@localhost~/testls-lrt chmod_examples-rw------- 1 example Domain Users 0 Jul 1511:42 chmod_examples
example@localhost~/testchmodg+wchmod_examples
example@localhost~/testls-lrt chmod_examples-rw--w---- 1 example Domain Users 0 Jul 1511:42 chmod_examples
In this chmod command example we will change permission onlyfor others class without affecting user and group class.
example@localhost~/testls-lrt chmod_examples-rw--w---- 1 example Domain Users 0 Jul 15
-
7/31/2019 Linux Set Date
15/101
11:42 chmod_examples
example@localhost~/testchmodo+wchmod_examples
example@localhost~/testls-lrt chmod_examples-rw--w--w- 1 example Domain Users 0 Jul 1511:42 chmod_examples
Chmod command Example 3: change file permissions for
all (user + group + others)In last unix chmod example we learn how to change permissionfor user, group and others individually but some time itsconvenient to change permissions for all instead of modifyingindividual permission for user, group and other.
If you are providing permission in text format than a is used forall while u is used for user.
example@localhost~/testls-lrtlinux_command.txt-rw--w--w- 1 example Domain Users 0 Jul 1511:42 linux_command.txt
example@localhost~/testchmoda+xlinux_command.txt
example@localhost~/testls-lrtlinux_command.txt-rwx-wx-wx 1 example Domain Users 0 Jul 1511:42 linux_command.txt*
Chmod command Example 4: Changing permissions innumeric format of chmod command
-
7/31/2019 Linux Set Date
16/101
Chmod command in UNIX and Linux allows modifyingpermissions not just on text format which is more readable butalso on numeric format where combination of permissions arerepresented in octal format e.g. 777 where first digit is for user,second is for group and 3rd is for others. Now if you write down1st digit in binary format it will be written as 111 on which 1st digitis for read permission, 2nd is for write and 3rd is for executepermission.
example@localhost~/testls-lrtunix_command.txt
-rw--w--w- 1 example Domain Users 0 Jul 1511:42 unix_command.txt
example@localhost~/testchmod777unix_command.txt
example@localhost~/testls-lrtunix_command.txt
-rwxrwxrwx 1 example Domain Users 0 Jul 1511:42 unix_command.txt*
Chmod command Example 5: How to remove filepermission using chmod command Unix
In this example of chmod command in UNIX we will see how toremove various permissions from files. You can easily removeread, write or execute permission from file using chmodcommand in both numeric and text format. Below examplesshows removal of execute permission represented by x in textformat.
example@localhost~/testls-lrtlinux_command.txt-rwx-wx-wx 1 example Domain Users 0 Jul 15
11:42 linux_command.txt*
-
7/31/2019 Linux Set Date
17/101
example@localhost~/testchmoda-xlinux_command.txt
example@localhost~/testls-lrt
linux_command.txt-rw--w--w- 1 example Domain Users 0 Jul 1511:42 linux_command.txt
Chmod command Example 6: changing permission fordirectory and subdirectory recursively in Unix
This is the most frequently used example of chmod command
where we want to provide permission to any directory and allcontents inside that directory including files and sub directories.By using R command option of chmod in Unix you can providepermissions recursively to any directory as shown in belowexample of chmod command.
example@localhost~/testls-lrttotal 8.0K-rwxrwxrwx 1 example Domain Users 0 Jul 1511:42 unix_command.txt*drwxr-xr-x+ 1 example Domain Users 0 Jul 1514:33 stocks/
example@localhost~/testchmod-R 777 stocks/
example@localhost~/testls-lrt
total 8.0K-rwxrwxrwx 1 example Domain Users 0 Jul 1511:42 unix_command.txt*drwxrwxrwx+ 1 example Domain Users 0 Jul 1514:33 stocks/
example@localhost~/testls-lrt stockstotal 0
-
7/31/2019 Linux Set Date
18/101
-rwxrwxrwx 1 example Domain Users 0 Jul 1514:33 online_stock_exchanges.txt*
Chmod command Example 7: How to remove read andwrite access from file for all
So far we have been seeing how to provide read, write andexecute permission to file and directory in UNIX and now we willsee opposite of that i.e. how to remove read, write and executeaccess. Its simple in text format because instead of + we aregoing to use -. Just like + used to add permission will be usedto remove permissions.
example@localhost~/testls-lrtstock_trading_systems-rwxrwxrwx 1 example Domain Users 0 Jul 1511:42 stock_trading_systems*
example@localhost~/testchmoda-wxstock_trading_systems
example@localhost~/testls-lrtstock_trading_systems-r--r--r-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systems
Chmod command Example 8: setting execute permission
only on directories without touching files
Many times we just want to provide directory or subdirectoryexecute permission without modifying permissions on file just tomake those directories searchable. Until I know this command Iused to do this by finding all directory and then changing thereexecute permission but we have a better way to do it by usingchmod command in UNIX. You can use "X" (capital X) options to
-
7/31/2019 Linux Set Date
19/101
provide execute permission to only directories without touchingfiles. Lets see an example of chmod command for that:
example@localhost~/testls-lrttotal 8.0K-r--r--r-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systemsdrw-rw-rw-+ 1 example Domain Users 0 Jul 1514:33 stocks/
example@localhost~/testchmoda+X *
example@localhost~/testls-lrttotal 8.0K-r--r--r-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systemsdrwxrwxrwx+ 1 example Domain Users 0 Jul 1514:33 stocks/
Remember to use X (capital case) if you use x (small case) it willaffect all files and directories.
Chmod command Example 9: changing mutiple permissionfor a file or directory in Unix or Linux
You can change combination of user + groups or groups+ otherin one command to modify permissions of files and directory.
Below example of chmod command just doing same itsproviding execute permission for user and read, executepermission
example@localhost~/testls-lrttotal 8.0K-r--r--r-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systems
drwxrwxrwx+ 1 example Domain Users 0 Jul 15
-
7/31/2019 Linux Set Date
20/101
14:33 stocks/
example@localhost~/testchmodu+x,g+xstock_trading_systems
example@localhost~/testls-lrtstock_trading_systems-r-xr-xr-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systems*
Chmod command Example 10: How to copy permission
from one file to another in UnixThis is very interesting example of chmod command in UNIXwhich copies permission from one file to another. You can easilyreference source file and copy all permissions on that file todestination file as shown in following chmod example:
example@localhost~/testls-lrt future_trading-rwxrwxrwx 1 example Domain Users 0 Jul 1515:30 future_trading*
example@localhost~/testls-lrtstock_trading_systems-r--r--r-- 1 example Domain Users 0 Jul 1511:42 stock_trading_systems
example@localhost~/testchmod
--reference=stock_trading_systemsfuture_trading
example@localhost~/testls-lrt future_trading-r--r--r-- 1 example Domain Users 0 Jul 1515:30 future_trading
-
7/31/2019 Linux Set Date
21/101
These were some offrequently used example of chmodcommand in UNIX or Linux. Chmod command is as useful asUNIX find command or grep command and knowing how tochange file permissions is essential skill while working in UNIX.Please share if you have any other example of chmod commandwhich we should be aware of.
Read more: http://javarevisited.blogspot.com/2012/03/10-example-of-chmod-command-in-unix.html#ixzz1ybsKBzU0
sort [OPTION]... [FILE]...DESCRIPTION
Write sorted concatenation of all FILE(s) to standard output.
Ordering options:
Mandatory arguments to long options are mandatory for short options
too.-b, --ignore-leading-blanks ignore leading blanks-d, --dictionary-order
consider only blanks and alphanumeric characters-f, --ignore-case
fold lower case to upper case characters-g, --general-numeric-sort
compare according to general numerical value
-i, --ignore-nonprintingconsider only printable characters
-M, --month-sortcompare (unknown) < `JAN' < ... < `DEC'
-n, --numeric-sortcompare according to string numerical value
-r, --reversereverse the result of comparisons
Other options:
http://javarevisited.blogspot.com/2011/03/10-find-command-in-unix-examples-basic.htmlhttp://javarevisited.blogspot.com/2012/03/10-example-of-chmod-command-in-unix.html#ixzz1ybsKBzU0http://javarevisited.blogspot.com/2012/03/10-example-of-chmod-command-in-unix.html#ixzz1ybsKBzU0http://javarevisited.blogspot.com/2011/03/10-find-command-in-unix-examples-basic.htmlhttp://javarevisited.blogspot.com/2012/03/10-example-of-chmod-command-in-unix.html#ixzz1ybsKBzU0http://javarevisited.blogspot.com/2012/03/10-example-of-chmod-command-in-unix.html#ixzz1ybsKBzU0 -
7/31/2019 Linux Set Date
22/101
-
7/31/2019 Linux Set Date
23/101
-
7/31/2019 Linux Set Date
24/101
4, Lady Gaga, Title 118, Price $6.306, Elvis Presley, Title 335, Price $6.305, Johnny Cash, Title 482, Price $6.502, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.907, John Lennon, Title 271, Price $7.90
The -r option will reverse the sorting. For example,
$ sort -k7 -r test.txt
Yields
7, John Lennon, Title 271, Price $7.903, Mick Jagger, Title 610, Price $7.902, Taylor Swift, Title 723, Price $7.905, Johnny Cash, Title 482, Price $6.506, Elvis Presley, Title 335, Price $6.304, Lady Gaga, Title 118, Price $6.301, Justin Timberlake, Title 545, Price $6.308, Michael Jackson, Title 373, Price $5.50
In order to save the sorted list in a file you could use the"redirect" operator:
sort -k7 -r test.txt > test_new.txt
where "test_new.txt" would be the new file. Of course
you can also apply the sort command to the output of a
stream, such as the "pipe" operator:
$ ls -al | sort -r -n -k5
This sorts the output of the file listing generated by ls by
file size, starting with largest files. The -n operator
specifies "numeric" sorting as compared to alphabetic.
http://linux.about.com/od/commands/l/blcmdl1_ls.htmhttp://linux.about.com/od/commands/l/blcmdl1_ls.htm -
7/31/2019 Linux Set Date
25/101
With + option it's possible to give a sorting key
man sort
Code:
`+POS1[-POS2]'The obsolete, traditional option for
specifying a sort field.The field consists of the line between
POS1 and up to but _notincluding_ POS2 (or the end of the line
if POS2 is omitted).Fields and character positions are
numbered starting with 0.
[...]
To sort the file below on the third field
(area code):
Jim Alchin 212121 SeattleBill Gates 404404 SeattleSteve Jobs 246810 NevadaScott Neally 212277 Los Angeles
$ sort -k 3,3 people.txt> sorted.txt
or using the 'old' syntax:$ sort +2 -3 people.txt> sorted2.txt
Have you tried the example?
Here more examples...
------------------------------------------------
-
7/31/2019 Linux Set Date
26/101
$ cat example.txt
Jon 200
Bill 30
Carl 100Bernard 5
$ sort -k 2 -n example.txt
Bernard 5
Bill 30
Carl 100
Jon 200------------------------------------------------
$ ls -l | sort -n -r -k 5
-rw-r--r-- 1 root root 1057 1 mar 20:12 ring+star
-rw-r--r-- 1 root root 727 1 mar 20:12 A_star
-rw-r--r-- 1 root root 535 1 mar 20:12 star2
-rw-r--r-- 1 root root 505 1 mar 20:12 spirals_and_stars
-rw-r--r-- 1 root root 503 1 mar 20:12 curves-rw-r--r-- 1 root root 475 1 mar 20:12 simily
-rw-r--r-- 1 root root 458 1 mar 20:12 ring
-rw-r--r-- 1 root root 415 1 mar 20:12 stars
-rw-r--r-- 1 root root 387 1 mar 20:12 sprial
-rw-r--r-- 1 root root 377 1 mar 20:12 polys
Task: Append Data To A Text File
To append (add data to existing) data to a file called foo.txt, enter:
cat >>foo.txt
-
7/31/2019 Linux Set Date
27/101
Task: Number All Output Lines
Type the following command:
cat -n filenamecat --number filename
Task: View Non-printing Characters
To display TAB characters as ^I, enter:
cat -T filename
To display $ at end of each line, enter:
cat -E filenamecat --show-ends filename
Use ^ and M- notation, except for LFD and TAB and show allnonprinting:
cat -v filenamecat --show-nonprinting filename
To show all, enter:
cat -A fileName
OR
-
7/31/2019 Linux Set Date
28/101
cat -vET fileName
Sample outputs:
Fig.02: Unix / Linux cat command: View Non-printing Characters
Viewing All Files
You can simply use the shell wildcard as follows:
cat *
To view only (c files) *.c files, enter:
http://bash.cyberciti.biz/guide/Wildcardshttp://www.cyberciti.biz/faq/linux-unix-appleosx-bsd-cat-command-examples/cat-nonprinting-characters/http://bash.cyberciti.biz/guide/Wildcards -
7/31/2019 Linux Set Date
29/101
cat *.c
Syntax:
The syntax is as follows:
cat file1cat > file2cat file3 | commandcat file4 | grep something
Examples:
cat file1cat file1 file2 > allcat file1 >> file2
What is wc ?
wc prints the number of lines, words and bytes in the given input. wc isthe abbreviation of word count.
3 wc Examples
Print the number of lines, words and characters in a file
To view the number of lines, words and characters in a file, give thefilename as argument to the wc command as shown below.
Syntax:
$ wc filenameX Y Z filename
-
7/31/2019 Linux Set Date
30/101
X Number of lines Y Number of words Z Number of bytes filename name of the file
$ wc demofile.txt36 104 570 demofile.txt
The above output indicates that the demofile.txt has 36 lines, 104words, and 570 bytes.
Print specific counts as required
You can use -l option to print only the line count as shown below.
$ wc -l demofile.txt36 demofile.txt
The same way you can use the following options for specificrequirements such as,
-w : print only word count -c : print only the byte count
You can also use any combination of above options.
Print the length of longest line
You can use -L option to print the length of longest line in the file.
$ wc -L demofile.txt84 demofile.txt
Syntax and Options
Short
Option
Long
OptionOption Description
-c bytes print the byte counts
-m chars print the character counts
-l lines print the newline counts
-
7/31/2019 Linux Set Date
31/101
-
7/31/2019 Linux Set Date
32/101
If we want to skip some initial bytes of input files and then start thecomparison then -i option can be used
$ cmp -i 5 file1.txt file2.txt
file1.txt file2.txt differ: byte 18, line 1
So we see that the initial 5 bytes were skipped and hence cmpcomplains that byte 18 differs (which in example 1 was byte 23)
3. Skip different number of initial bytes from both input files
Another case could be when we would want to skip x bytes of inputin file1 and y bytes of input in file2. This could be achieved as
follows :
$ cmp -i 5:2 file1.txt file2.txtfile1.txt file2.txt differ: byte 2, line 1
So we see that we can give the option -i with x:y kind of input for thiscase. The output shows that this time the difference occurred very earlyat the second byte.
4. Display bytes that differ
If in the example 3 above we would also like to know the values ofindividual differing bytes being compared then the -l option can beused
$ cmp -l -i 5:2 file1.txt file2.txt2 156 115
3 141 1714 155 405 145 1566 40 1417 151 1558 163 14510 110 15111 151 163
12 155 4013 141 110
-
7/31/2019 Linux Set Date
33/101
-
7/31/2019 Linux Set Date
34/101
default)
-l verboseOutput byte numbers andvalues of all differing bytes.
-n LIMIT bytes=LIMIT Compare at most LIMIT bytes.-s quiet silent
Output nothing; yield exitstatus only.
-v version Output version info.
help Output this help.
Comm.
NAMEcomm - select or reject lines common to two files
SYNOPSIScomm [-123] file1 file2
OPTIONSThe following options are supported:
-1 Suppresses the output column of lines unique tofile1.
-2 Suppresses the output column of lines unique tofile2.
-3 Suppresses the output column of lines duplicated in
file1 and file2.
NAME
diff - find differences between two files
SYNOPSIS
diff[options] from-file to-file
-
7/31/2019 Linux Set Date
35/101
DESCRIPTION
In the simplest case, diffcompares the contents of the two filesfrom-file and to-file. A file name of- stands for text read from the standard
input. As a special case, diff - - compares a copy of standard input toitself.
Iffrom-file is a directory and to-file is not, diffcompares the file infrom-file whose file name is that ofto-file, and vice versa. The non-directory file must not be -.
If bothfrom-file and to-file are directories, diffcompares corresponding
files in both directories, in alphabetical order; this comparison is notrecursive unless the -r or--recursive option is given. diffnevercompares the actual contents of a directory as if it were a file. The filethat is fully specified may not be standard input, because standard inputis nameless and the notion of ``file with the same name'' does notapply.
diffoptions begin with -, so normallyfrom-file and to-file may notbegin with -. However, -- as an argument by itself treats the remaining
arguments as file names even if they begin with -.
Options
Below is a summary of all of the options that GNU diffaccepts. Mostoptions have two equivalent names, one of which is a single letterpreceded by -, and the other of which is a long name preceded by --.Multiple single letter options (unless they take an argument) can be
combined into a single command line word: -ac is equivalent to -a -c.Long named options can be abbreviated to any unique prefix of theirname. Brackets ([ and ]) indicate that an option takes an optionalargument.-lines
Show lines (an integer) lines of context. This option does notspecify an output format by itself; it has no effect unless it iscombined with -c or-u. This option is obsolete. For proper
operation,patch typically needs at least two lines of context.-a
-
7/31/2019 Linux Set Date
36/101
Treat all files as text and compare them line-by-line, even if theydo not seem to be text.
-bIgnore changes in amount of white space.
-BIgnore changes that just insert or delete blank lines.
--briefReport only whether the files differ, not the details of thedifferences.
-cUse the context output format.
-C lines
--context[=lines]Use the context output format, showing lines (an integer) lines ofcontext, or three iflines is not given. For proper operation,patchtypically needs at least two lines of context.
--changed-group-format=formatUseformatto output a line group containing differing lines fromboth files in if-then-else format.
-dChange the algorithm to perhaps find a smaller set of changes.This makes diffslower (sometimes much slower).
-D nameMake merged if-then-else format output, conditional on thepreprocessor macro name.
-e
--edMake output that is a valid edscript.
--exclude=patternWhen comparing directories, ignore files and subdirectorieswhose basenames matchpattern.
--exclude-from=fileWhen comparing directories, ignore files and subdirectorieswhose basenames match any pattern contained infile.
--expand-tabs
-
7/31/2019 Linux Set Date
37/101
Expand tabs to spaces in the output, to preserve the alignment oftabs in the input files.
-fMake output that looks vaguely like an edscript but has changesin the order they appear in the file.
-F regexpIn context and unified format, for each hunk of differences, showsome of the last preceding line that matches regexp.
--forward-edMake output that looks vaguely like an ed script but has changesin the order they appear in the file.
-h
This option currently has no effect; it is present for Unixcompatibility.
-HUse heuristics to speed handling of large files that have numerousscattered small changes.
--horizon-lines=linesDo not discard the last lines lines of the common prefix and thefirst lines lines of the common suffix.
-iIgnore changes in case; consider upper- and lower-case lettersequivalent.
-I regexpIgnore changes that just insert or delete lines that match regexp.
--ifdef=nameMake merged if-then-else format output, conditional on thepreprocessor macro name.
--ignore-all-spaceIgnore white space when comparing lines.
--ignore-blank-linesIgnore changes that just insert or delete blank lines.
--ignore-caseIgnore changes in case; consider upper- and lower-case to be thesame.
--ignore-matching-lines=regexp
Ignore changes that just insert or delete lines that match regexp.
-
7/31/2019 Linux Set Date
38/101
--ignore-space-changeIgnore changes in amount of white space.
--initial-tabOutput a tab rather than a space before the text of a line in normalor context format. This causes the alignment of tabs in the line tolook normal.
-lPass the output throughprto paginate it.
-L label
--label=labelUse labelinstead of the file name in the context format and
unified format headers.--left-column
Print only the left column of two common lines in side by sideformat.
--line-format=formatUseformatto output all input lines in in-then-else format.
--minimalChange the algorithm to perhaps find a smaller set of changes.
This makes diffslower (sometimes much slower).-n
Output RCS-format diffs; like -fexcept that each commandspecifies the number of lines affected.
-N
--new-fileIn directory comparison, if a file is found in only one directory,
treat it as present but empty in the other directory.--new-group-format=format
Useformatto output a group of lines taken from just the secondfile in if-then-else format.
--new-line-format=formatUseformatto output a line taken from just the second file in if-then-else format.
--old-group-format=format
-
7/31/2019 Linux Set Date
39/101
Useformatto output a group of lines taken from just the first filein if-then-else format.
--old-line-format=formatUseformatto output a line taken from just the first file in if-then-else format.
-pShow which C function each change is in.
-PWhen comparing directories, if a file appears only in the seconddirectory of the two, treat it as present but empty in the other.
--paginatePass the output throughprto paginate it.
-qReport only whether the files differ, not the details of thedifferences.
-rWhen comparing directories, recursively compare anysubdirectories found.
--rcsOutput RCS-format diffs; like -fexcept that each command
specifies the number of lines affected.--recursive
When comparing directories, recursively compare anysubdirectories found.
--report-identical-files
-sReport when two files are the same.
-SfileWhen comparing directories, start with the filefile. This is usedfor resuming an aborted comparison.
--from-file=fileComparefile to all operands.file can be a directory.
--to-file=fileCompare all operands tofile. file can be a directory.
--sdiff-merge-assist
-
7/31/2019 Linux Set Date
40/101
Print extra information to helpsdiff.sdiffuses this option when itruns diff. This option is not intended for users to use directly.
--show-c-functionShow which C function each change is in.
--show-function-line=regexpIn context and unified format, for each hunk of differences, showsome of the last preceding line that matches regexp.
--side-by-sideUse the side by side output format.
--speed-large-filesUse heuristics to speed handling of large files that have numerousscattered small changes.
--starting-file=fileWhen comparing directories, start with the filefile. This is usedfor resuming an aborted comparison.
--suppress-common-linesDo not print common lines in side by side format.
-tExpand tabs to spaces in the output, to preserve the alignment oftabs in the input files.
-TOutput a tab rather than a space before the text of a line in normalor context format. This causes the alignment of tabs in the line tolook normal.
--textTreat all files as text and compare them line-by-line, even if theydo not appear to be text.
-u
Use the unified output format.--unchanged-group-format=format
Useformatto output a group of common lines taken from bothfiles in if-then-else format.
--unchanged-line-format=formatUseformatto output a line common to both files in if-then-elseformat.
--unidirectional-new-file
-
7/31/2019 Linux Set Date
41/101
When comparing directories, if a file appears only in the seconddirectory of the two, treat it as present but empty in the other.
-U lines
--unified[=lines]Use the unified output format, showing lines (an integer) lines ofcontext, or three iflines is not given. For proper operation,patchtypically needs at least two lines of context.
-v
--versionOutput the version number ofdiff.
-wIgnore white space when comparing lines.
-W columns
--width=columnsUse an output width ofcolumns in side by side format.
-xpatternWhen comparing directories, ignore files and subdirectories
whose basenames matchpattern.-Xfile
When comparing directories, ignore files and subdirectorieswhose basenames match any pattern contained infile.
-yUse the side by side output format.
Environmental Commands
logout orexit end terminal session
passwd change password
date print date & time
whoami orwho am i
list current user in that window
who list all users logged onto the workstation
-
7/31/2019 Linux Set Date
42/101
man
command1print on-line UNIX manual page forcommand1
ftp hostname
start file transfer protocol to transfer file between localand remote workstations. Remote workstation is namedhostname
telnet
hostnamelog onto remote workstation named hostname
df -k print list of disks and current capacity (in kilobytes)
setenv list environmental variables
which
commandlist location of executable command
File Manipulation
ls
list contents of current directory. Examples:lsfile.1 lists presence offile.1ls -l lists presence offile.1 with expandedinformationls -a lists contents of current directory, including filesthat start with "."
jotfile.1 opensjot editor; readsfile.1 intojot for editing
catfile.1 show contents offile.1 on screen
morefile.1show contents offile.1 on screen, but doesn't scrollpast top of screen
headfile.1 show first 20 lines offile.1 on screen
tailfile.1 show last 20 lines offile.1 on screen
difffile.1 file.2 shows differences betweenfile.1 andfile.2
wc
counts lines, words, and characters in filefile.1.Variations:wc -l counts lines in filefile.1wc -w counts words in filefile.1wc -m counts characters in filefile.1
cpfile.1 file.2copiesfile.1 tofile.2. Iffile.2 exists, it is overwritten.Originalfile.1 is not removed
mvfile.1 file.2movesfile.1 tofile.2. Iffile.2 exists, it is overwritten.
Originalfile.1 is removedrmfile.1 removefile.1. No utilities exist to retrieve it
-
7/31/2019 Linux Set Date
43/101
grep PATTERN
file.1print all lines that contain PATTERN infile.1
lprfile.1 printfile.1 on default laser printer
lpr Show list of available printers and questions to directyour printing of a file to a particular printer
du -sk
print size (in kilobytes) of current directory (".").Variations:du -sk * prints sizes (in kilobytes) of all files andsub-directoriesdu -skfile.1 prints size (in kilobytes) offile.1
compressfile.1
reduce the size offile.1 and replace it with a file
namedfile.1.Z. This compressed file is NOT a(readable) ASCII file.
uncompress
file.1.Zrestore the compressed filefile.1.Z
find . -name
file.1 -print
find the loation offile.1 in the directory and sub-directories. Variations:find . -name "*pattern" -print finds all files thatend withpattern.
find . -namefile.1 -exec rm '{}' ';' removes all filesnamedfile.1.
greppattern
file.1print only the lines offile.1 that containpattern
sortfile.1
displays contents offile.1 sorted alphabetically.Variations:sort -nfile.1 displays contents offile.1 sortednumerically
sort -rfile.1 displays contents offile.1 sortedalphabetically in reverse order.
Directory Manipulation
pwdshow the directory that you are in (present workingdirectory)
cd dir.1 change directory to dir.1
mkdir dir.1 make new directory dir.1
-
7/31/2019 Linux Set Date
44/101
rmdir dir.1 remove EMPTY directory dir.1
rm -r dir.1 remove directory dir.2 AND its contents
cp -r dir.1 dir.2 copy dir.1 (and its contents) to dir.2
mvfile.1 dir.1 movefile.1 to dir.1
ls
show contents of current directory. Variations:ls dir.1 shows contents ofdir.1ls -d dir.1 shows PRESENCE ofdir.1
du -skdir.1show sum of size (in kilobytes) ofdir.1 and itscontents
tar -cvfdir.1.tar
dir.1store an image ofdir.1 and it's contents in filefile.1
Process Control
command1& execute command1 in background
ps -ef print expanded list of all processes
killpid1 remove processpid1
interrupt current process
suspend current process
jobs display background and suspended processeskill %1 remove suspended process #1
top display the current, most computer-intensive commands
osview display the operating system statitistics
System Security
The following mechanism is the ONLY guaranteed method ofprotecting your work.
Each file and directory is owned by a user, and each user belongs to agroup. By default, users own their home directory (the current directorywhen the user logs in) and the contents of the home directory. Most
other files and directories are owned by "root" and other special users.
-
7/31/2019 Linux Set Date
45/101
The user assigns a type of privilege to each file and directory owned bythe user. By default, the privilege is rwxr-xr-x.
The first three characters ofrwxr-xr-x indicate that the owner can
read, write, and execute the file (or directory). The middle threecharacters indicate that all other users in the same group as the ownercan read and execute the file (or directory), but cannot write onto thefile (or directory), as indicated by the middle "-" character. The lastthree characters indicate that everyone else on the system can read andexecute the file (or directory), but cannot write onto the file (ordirectory), as indicated by the last "-" character.
To change the owner's permissions of a file (or directory), the ownercan type:
chown u+r file.1 chown u+w file.1 chown u+xfile.1
chown u-r file.1 chown u-w file.1 chown u-xfile.1
To change the group's permissions of a file (or directory), the ownercan type:chown g+r file.1 chown g+w file.1 chown g+xfile.1
chown g-r file.1 chown g-w file.1 chown g-xfile.1
To change the permissions of a file (or directory) for everyone else, theowner can type:chown o+r file.1 chown o+w file.1 chown o+xfile.1
chown o-r file.1 chown o-w file.1 chown o-xfile.1
SYNOPSIS
-
7/31/2019 Linux Set Date
46/101
touch [-acm] [-fagefile] [-ragefile] [[-t] time]file ...
touch [-acm] timefile ...
DESCRIPTION
The touch command changes certain dates for eachfile argument. By
default, touch sets both the date of last file modification and the date
of last file access to the current time. This is useful for maintainingcorrect release times for software and is particularly useful inconjunction with the MKS Make software development facility.
Options
-a
sets only the access time.
-c
does not create anyfiles that do not already exist. Normally,touch creates such files.
-m
sets only the modification time.
If you do not specify -a or-m, touch behaves as though you
specified both.
To tell touch to use a time other than the current, use one of the
following options:
-fagefile
is an obsolete version of the POSIX-compliant -r option.
-ragefile
-
7/31/2019 Linux Set Date
47/101
sets the access and modification times (as indicated by the otheroptions) to those kept foragefile.
-ttime
specifies a particular time using this format:
[[[[cc]yy]MM]dd]hhmm[.ss]
where cc is the optional first 2 digits of the year,yy is the optionallast 2 digits of the year,MMis the optional number of the month(01-12), ddis the optional day of the month, hh is the hour in 24hour format (required), mm is the minutes (required),ss is theoptional seconds.
An obsolete (but still supported) version of this command lets you omitthe -t, but the format is:
MMddhhmmyy[yy]
EXAMPLES
touch newfile
sets the modification time ofnewfile to the present.
touch -t 8001031305 oldfile
sets the modification time ofoldfile to 13:05 on January 3, 1980.
touch -r oldfile newfile
sets the modification time ofnewfile to that ofoldfile.
The unix touch command
Posted on September 11, 2008
http://charles.lescampeurs.org/2008/09/11/the-unix-touch-commandhttp://charles.lescampeurs.org/2008/09/11/the-unix-touch-command -
7/31/2019 Linux Set Date
48/101
This post is a quick ref on the linux touch command. All the exampleshave been tested on Linux.
This command is used to update the access and modification times of
files.
touchs syntax
touch [option] file_name(s)touch file1 file2 file3
Here some examples:
# touch /tmp/file# ls -l /tmp/filerw-r--r-- 1 charlybr charlybr 0 Sep 10 16:13/tmp/file
Update access and modification time to currenttime:
# ls -l /tmp/filerw-r--r-- 1 charlybr charlybr 0 Sep 10 16:13/tmp/file# touch /tmp/file# ls -l /tmp/filerw-r--r-- 1 charlybr charlybr 0 Sep 10 16:14/tmp/file
Update access and modification time to a specified
timestamp ([[CC]YY]MMDDhhmm[.ss] format):
# touch -t 09091842 /tmp/file# ls -l /tmp/file-rw-r--r-- 1 charlybr charlybr 0 Sep 918:42 /tmp/file
Update access and modification time to a specified
date
-
7/31/2019 Linux Set Date
49/101
# touch -d '9 Sep' /tmp/file# ls -l /tmp/file-rw-r--r-- 1 charlybr charlybr 0 Sep 900:00 /tmp/file
# touch -d '9 Sep 2008 13:14' /tmp/file# ls -l /tmp/file-rw-r--r-- 1 charlybr charlybr 0 Sep 913:14 /tmp/file
Hack 25. Cut Command Examples
by Ramesh
Cut command can be used to display only specific columns from a textfile or other command outputs.
Following are some of the examples.
Display the 1st field (employee name) from a colon delimited file
$ cut -d: -f 1 names.txt
Emma ThomasAlex JasonMadison RandySanjay GuptaNisha Singh
Display 1st and 3rd field from a colon delimited file
$ cut -d: -f 1,3 names.txt
Emma Thomas:MarketingAlex Jason:SalesMadison Randy:Product DevelopmentSanjay Gupta:Support
Nisha Singh:Sales
-
7/31/2019 Linux Set Date
50/101
-
7/31/2019 Linux Set Date
51/101
-
7/31/2019 Linux Set Date
52/101
ood osgood os
If you omit the start and end positions, then the cut command prints theentire line.
cut -c- file.txt
3.Write a unix/linux cut command to print the fields using thedelimiter?
You can use the cut command just as awk command to extract the
fields in a file using a delimiter. The -d option in cut command can beused to specify the delimiter and -f option is used to specify the fieldposition.
cut -d' ' -f2 file.txtorunixlinux
This command prints the second field in each line by treating the spaceas delimiter. You can print more than one field by specifying theposition of the fields in a comma delimited list.
cut -d' ' -f2,3 file.txtor linuxunix goodlinux good
The above command prints the second and third field in each line.
Note: If the delimiter you specified is not exists in the line, then the cutcommand prints the entire line. To suppress these lines use the -soption in cut command.
4. Write a unix/linux cut command to display range of fields?
You can print a range of fields by specifying the start and end position.
-
7/31/2019 Linux Set Date
53/101
cut -d' ' -f1-3 file.txt
The above command prints the first, second and third fields. To printthe first three fields, you can ignore the start position and specify onlythe end position.
cut -d' ' -f-3 file.txt
To print the fields from second fields to last field, you can omit the lastfield position.
cut -d' ' -f2- file.txt
5. Write a unix/linux cut command to display the first field from/etc/passwd file?
The /etc/passwd is a delimited file and the delimiter is a colon (:). Thecut command to display the first field in /etc/passwd file is
cut -d':' -f1 /etc/passwd
6. The input file contains the below text
> cat filenames.txtlogfile.datsum.pladd_int.sh
Using the cut command extract the portion after the dot.
First reverse the text in each line and then apply the command on it.
rev filenames.txt | cut -d'.' -f1
Unix Shell commands
- 9:07 AM - 11 comments
http://www.scripterworld.com/search/label/Unix%20Shell%20commandshttp://www.scripterworld.com/2009/11/unix-cut-command-with-real-examples.html#comment-formhttp://www.scripterworld.com/search/label/Unix%20Shell%20commandshttp://www.scripterworld.com/2009/11/unix-cut-command-with-real-examples.html#comment-form -
7/31/2019 Linux Set Date
54/101
Unix cut command with real examples
Uinx Cut command displays selected sections from each line of
a file.
Unix Cut command Syntax :
cut [OPTION]... [FILE]...
Linux Cut commnd options with examples
Unix cut command treats input data is made up of one range, or
many ranges separated by delimiter.
N character or field, counted from 1
N- from Nth byte, character or field, to end of line
N-M from Nth to Mth (included) byte, character or field
-M from first to Mth (included) byte, character or field
Let see the options of unix commands with examples.
My sample file contents
$ cat passwdfile
unixuser:x:501:506:Unix
User:/home/unixuser:/bin/bash
oradba:x:502:506:DBA
User:/home/oradba:/bin/bash
http://www.scripterworld.com/2009/11/unix-cut-command-with-real-examples.htmlhttp://www.scripterworld.com/2009/11/unix-cut-command-with-real-examples.html -
7/31/2019 Linux Set Date
55/101
scripter:x:1658:506:Scripter
World:/home/scripter:/bin/bash
$
Unix cut c option
-c option specifies to output to display only these character
positions.
To display output of 10 character(N character) of each line
$ cut -c 10 passwdfile
x
5
x
$
To display output of 5 and 10 characters(N,M characters) ofeach line
$ cut -c 5,10 passwdfile
ux
b5
px
$
To display output from 5th to 10th characters(N-M characters) of
each line
$ cut -c 5-10 passwdfile
user:x
-
7/31/2019 Linux Set Date
56/101
ba:x:5
pter:x
$
To display output upto 10th character(-M charcters) of each line
$ cut -c -10 passwdfile
unixuser:x
oradba:x:5
scripter:x
$
To display output from 10th character(N- charcters) to end of the
each line
$ cut -c 10- passwdfile
x:501:506:Unix User:/home/unixuser:/bin/bash
502:506:DBA User:/home/oradba:/bin/bashx:1658:506:Scripter
World:/home/scripter:/bin/bash
$
Unix cut -d option and Unix cut -f option
-d The character following -d is the field delimiter . Default is tab.Space or other characters with special meaning to the shell must
be quoted. delim can be a multi-byte character.
-f specifies the fields to display from the list of fields formed from
the input data separate by delimter(-d) .Fields are counted from
one and separate multiple values by comma (,)
To get the user description(5th field) from our example file
-
7/31/2019 Linux Set Date
57/101
-
7/31/2019 Linux Set Date
58/101
Scripter World:/home/scripter:/bin/bash
$
Unix cut last characterTo display a last character of a string
STRING="unixuser:x:501:506:Unix
User:/home/unixuser:/bin/bash"
echo ${STRING} awk '$0=$NF' FS=
$ STRING="unixuser:x:501:506:UnixUser:/home/unixuser:/bin/bash"
$ echo ${STRING} awk '$0=$NF' FS=h$
Use cut last field or columnTo display a last field of a string with a delimter (Here delimter is
":" colon)
STRING="unixuser:x:501:506:Unix
User:/home/unixuser:/bin/bash"
echo ${STRING} awk '$0=$NF' FS=":"
$ STRING="unixuser:x:501:506:Unix
User:/home/unixuser:/bin/bash"
$ echo ${STRING} awk '$0=$NF' FS=":"
/bin/bash
$
-
7/31/2019 Linux Set Date
59/101
First create the following demo_file that will be used in the examplesbelow to demonstrate grep command.
$ cat demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THISFILE.this line is the 1st lower case line in thisfile.This Line Has All Its First Character Of TheWord With Upper Case.
Two lines above this line is empty.
And this is the last line.
1. Search for the given string in a single file
The basic usage of grep command is to search for a specific string inthe specified file as shown below.
Syntax:grep "literal_string" filename
$ grep "this" demo_filethis line is the 1st lower case line in thisfile.Two lines above this line is empty.
2. Checking for the given string in multiple files.
Syntax:grep "string" FILE_PATTERN
This is also a basic usage of grep command. For this example, let uscopy the demo_file to demo_file1. The grep output will also include thefile name in front of the line that matched the specific pattern as shownbelow. When the Linux shell sees the meta character, it does theexpansion and gives all the files as input to grep.
$ cp demo_file demo_file1
-
7/31/2019 Linux Set Date
60/101
$ grep "this" demo_*demo_file:this line is the 1st lower case linein this file.demo_file:Two lines above this line is empty.
demo_file:And this is the last line.demo_file1:this line is the 1st lower case linein this file.demo_file1:Two lines above this line is empty.demo_file1:And this is the last line.
3. Case insensitive search using grep -i
Syntax:grep -i "string" FILE
This is also a basic usage of the grep. This searches for the givenstring/pattern case insensitively. So it matches all the words such asthe, THE and The case insensitively as shown below.
$ grep -i "the" demo_file
THIS LINE IS THE 1ST UPPER CASE LINE IN THISFILE.this line is the 1st lower case line in thisfile.This Line Has All Its First Character Of TheWord With Upper Case.And this is the last line.
4. Match regular expression in files
Syntax:grep "REGEX" filename
This is a very powerful feature, if you can use use regular expressioneffectively. In the following example, it searches for all the pattern thatstarts with lines and ends with empty with anything in-between. i.e
To search lines[anything in-between]empty in the demo_file.
-
7/31/2019 Linux Set Date
61/101
-
7/31/2019 Linux Set Date
62/101
The following example is the WORD grep where it is searching onlyfor the word is. Please note that this output does not contain the lineThis Line Has All Its First Character Of The Word With Upper Case,even though is is there in the This, as the following is looking onlyfor the word is and not for this.
$ grep -iw "is" demo_fileTHIS LINE IS THE 1ST UPPER CASE LINE IN THISFILE.this line is the 1st lower case line in thisfile.
Two lines above this line is empty.And this is the last line.
6. Displaying lines before/after/around the match using grep -A,
-B and -C
When doing a grep on a huge file, it may be useful to see some linesafter the match. You might feel handy if grep can show you not onlythe matching lines but also the lines after/before/around the match.
Please create the following demo_text file for this example.
$ cat demo_text4. Vim Word Navigation
You may want to do several navigation in
relation to the words, such as:
* e - go to the end of the current word.* E - go to the end of the current WORD.* b - go to the previous (before) word.* B - go to the previous (before) WORD.* w - go to the next word.* W - go to the next WORD.
-
7/31/2019 Linux Set Date
63/101
-
7/31/2019 Linux Set Date
64/101
$ grep -B 2 "single WORD" demo_textExample to show the difference between WORD andword
* 192.168.1.1 - single WORD
6.3 Display N lines around match
-C is the option which prints the specified N lines before the match. Insome occasion you might want the match to be appeared with the linesfrom both the side. This options shows N lines in both the side(before& after) of match.
$ grep -C 2 "Example" demo_textword - word consists of a sequence of letters,digits and underscores.
Example to show the difference between WORD andword
* 192.168.1.1 - single WORD
7. Highlighting the search using GREP_OPTIONS
As grep prints out lines from the file by the pattern / string you hadgiven, if you wanted it to highlight which part matches the line, thenyou need to follow the following way.
When you do the following export you will get the highlighting of the
matched searches. In the following example, it will highlight all the thiswhen you set the GREP_OPTIONS environment variable as shownbelow.
$ export GREP_OPTIONS='--color=auto'GREP_COLOR='100;8'
$ grep this demo_filethis line is the 1st lower case line in thisfile.
-
7/31/2019 Linux Set Date
65/101
Two lines above this line is empty.And this is the last line.
8. Searching in all files recursively using grep -r
When you want to search in all the files under the current directory andits sub directory. -r option is the one which you need to use. Thefollowing example will look for the string ramesh in all the files inthe current directory and all its subdirectory.
$ grep -r "ramesh" *
9. Invert match using grep -v
You had different options to show the lines matched, to show the linesbefore match, and to show the lines after match, and to highlight match.So definitely Youd also want the option -v to do invert match.
When you want to display the lines which does not matches the givenstring/pattern, use the option -v as shown below. This example willdisplay all the lines that did not match the word go.
$ grep -v "go" demo_text4. Vim Word Navigation
You may want to do several navigation inrelation to the words, such as:
WORD - WORD consists of a sequence of non-blank
characters, separated with white space.word - word consists of a sequence of letters,digits and underscores.
Example to show the difference between WORD andword
* 192.168.1.1 - single WORD* 192.168.1.1 - seven words.
-
7/31/2019 Linux Set Date
66/101
10. display the lines which does not matches all the given pattern.
Syntax:grep -v -e "pattern" -e "pattern"
$ cat test-file.txtabcd
$ grep -v -e "a" -e "b" -e "c" test-file.txtd
11. Counting the number of matches using grep -c
When you want to count that how many lines matches the givenpattern/string, then use the option -c.
Syntax:grep -c "pattern" filename$ grep -c "go" demo_text
6
When you want do find out how many lines matches the pattern
$ grep -c this demo_file3
When you want do find out how many lines that does not match thepattern
$ grep -v -c this demo_file4
12. Display only the file names which matches the given pattern
using grep -l
-
7/31/2019 Linux Set Date
67/101
If you want the grep to show out only the file names which matched thegiven pattern, use the -l (lower-case L) option.
When you give multiple files to the grep as input, it displays the namesof file which contains the text that matches the pattern, will be veryhandy when you try to find some notes in your whole directorystructure.
$ grep -l this demo_*demo_filedemo_file1
13. Show only the matched string
By default grep will show the line which matches the givenpattern/string, but if you want the grep to show out only the matchedstring of the pattern then use the -o option.
It might not be that much useful when you give the string straightforward. But it becomes very useful when you give a regex pattern andtrying to see what it matches as
$ grep -o "is.*line" demo_fileis line is the 1st lower case lineis lineis is the last line
14. Show the position of match in the line
When you want grep to show the position where it matches the patternin the file, use the following options as
Syntax:grep -o -b "pattern" file$ cat temp-file.txt1234512345
$ grep -o -b "3" temp-file.txt
-
7/31/2019 Linux Set Date
68/101
2:38:3
Note: The output of the grep command above is not the position in theline, it is byte offset of the whole file.
15. Show line number while displaying the output using grep -n
To show the line number of file with the line matched. It does 1-basedline numbering for each file. Use -n option to utilize this feature.
$ grep -n "go" demo_text
5: * e - go to the end of the current word.6: * E - go to the end of the current WORD.7: * b - go to the previous (before) word.8: * B - go to the previous (before) WORD.9: * w - go to the next word.10: * W - go to the next WORD.
Additional Grep Tutorials
7 Linux Grep OR, Grep AND, Grep NOT OperatorExamples
Regular Expressions in Grep Command with 10Examples Part I
Advanced Regular Expressions in Grep Commandwith 10 Examples Part II
Search in a *.bz2 file using bzgrep, and *.gz file
using zgrep
Awesome Linux Articles
Following are few awesome 15 examples articles that you might findhelpful.
Linux Crontab: 15 Awesome Cron Job Examples Mommy, I found it! 15 Practical Linux Find
Command Examples 15 Examples To Master Linux Command Line History
http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/http://www.thegeekstuff.com/2011/01/regular-expressions-in-grep-command/http://www.thegeekstuff.com/2011/01/regular-expressions-in-grep-command/http://www.thegeekstuff.com/2011/01/advanced-regular-expressions-in-grep-command-with-10-examples-%E2%80%93-part-ii/http://www.thegeekstuff.com/2011/01/advanced-regular-expressions-in-grep-command-with-10-examples-%E2%80%93-part-ii/http://www.thegeekstuff.com/2010/10/bzcommand-examples/http://www.thegeekstuff.com/2009/05/zcat-zless-zgrep-zdiff-zcmp-zmore-gzip-file-operations-on-the-compressed-files/http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/http://www.thegeekstuff.com/2011/01/regular-expressions-in-grep-command/http://www.thegeekstuff.com/2011/01/regular-expressions-in-grep-command/http://www.thegeekstuff.com/2011/01/advanced-regular-expressions-in-grep-command-with-10-examples-%E2%80%93-part-ii/http://www.thegeekstuff.com/2011/01/advanced-regular-expressions-in-grep-command-with-10-examples-%E2%80%93-part-ii/http://www.thegeekstuff.com/2010/10/bzcommand-examples/http://www.thegeekstuff.com/2009/05/zcat-zless-zgrep-zdiff-zcmp-zmore-gzip-file-operations-on-the-compressed-files/http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/ -
7/31/2019 Linux Set Date
69/101
Unix LS Command: 15 Practical Examples
Share
Comment
If you enjoyed this article, you might also like..
1. 50 Linux SysadminTutorials
2. 50 Most FrequentlyUsed Linux Commands(With Examples)
3. Top 25 Best LinuxPerformance Monitoringand Debugging Tools
4. Mommy, I found it! 15Practical Linux FindCommand Examples
5. Linux 101 Hacks 2nd
Edition eBook
Awk Introduction 7Awk Print Examples
Advanced SedSubstitution Examples
8 Essential Vim Editor
NavigationFundamentals
25 Most FrequentlyUsed Linux IPTablesRules Examples
Turbocharge PuTTYwith 12 Powerful Add-
Ons
Tags: File Search Utility, Grep Command, Highlight
Search Output, Linux Full-Text Searching, Linux Grep
Command, Search File Content, Search Multiple Files
{ 75 comments read them below oradd one }
http://www.thegeekstuff.com/2009/07/linux-ls-command-examples/http://www.addthis.com/bookmark.php?v=250&pub=xa-4ac6c0d77fc11b75http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#respondhttp://www.thegeekstuff.com/2010/12/50-unix-linux-sysadmin-tutorials/http://www.thegeekstuff.com/2010/12/50-unix-linux-sysadmin-tutorials/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/linux-101-hacks-ebook/http://www.thegeekstuff.com/linux-101-hacks-ebook/http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-advanced-sed-substitution-examples/http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-advanced-sed-substitution-examples/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/tag/file-search-utility/http://www.thegeekstuff.com/tag/grep-command/http://www.thegeekstuff.com/tag/highlight-search-output/http://www.thegeekstuff.com/tag/highlight-search-output/http://www.thegeekstuff.com/tag/linux-full-text-searching/http://www.thegeekstuff.com/tag/linux-grep-command/http://www.thegeekstuff.com/tag/linux-grep-command/http://www.thegeekstuff.com/tag/search-file-content/http://www.thegeekstuff.com/tag/search-multiple-files/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#respondhttp://www.thegeekstuff.com/vim-101-hacks-ebook/http://www.thegeekstuff.com/nagios-core-ebook/http://www.thegeekstuff.com/sed-awk-101-hacks-ebook/http://www.thegeekstuff.com/bash-101-hacks-ebook/http://www.thegeekstuff.com/2009/07/linux-ls-command-examples/http://www.addthis.com/bookmark.php?v=250&pub=xa-4ac6c0d77fc11b75http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#respondhttp://www.thegeekstuff.com/2010/12/50-unix-linux-sysadmin-tutorials/http://www.thegeekstuff.com/2010/12/50-unix-linux-sysadmin-tutorials/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2010/11/50-linux-commands/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2011/12/linux-performance-monitoring-tools/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/linux-101-hacks-ebook/http://www.thegeekstuff.com/linux-101-hacks-ebook/http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-advanced-sed-substitution-examples/http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-advanced-sed-substitution-examples/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2009/03/8-essential-vim-editor-navigation-fundamentals/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2011/06/iptables-rules-examples/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/2008/08/turbocharge-putty-with-12-powerful-add-ons-software-for-geeks-3/http://www.thegeekstuff.com/tag/file-search-utility/http://www.thegeekstuff.com/tag/grep-command/http://www.thegeekstuff.com/tag/highlight-search-output/http://www.thegeekstuff.com/tag/highlight-search-output/http://www.thegeekstuff.com/tag/linux-full-text-searching/http://www.thegeekstuff.com/tag/linux-grep-command/http://www.thegeekstuff.com/tag/linux-grep-command/http://www.thegeekstuff.com/tag/search-file-content/http://www.thegeekstuff.com/tag/search-multiple-files/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#respond -
7/31/2019 Linux Set Date
70/101
1Joao Trindade March 28, 2009 at 3:54 am
You have a small glitch:>> 4. Match regular expression in files using grep -i
Dont you mean:4. Match regular expression in files using grep -e
The rest of the post is great.
2 Ramesh March 29, 2009 at 12:16 am
Joao,
Thanks for pointing it out. I have corrected it. Also, we can doREGEX without the option -e as shown in the example #4.
From Man Pages:
SYNOPSIS
grep [options] PATTERN [FILE...]grep [options] [-e PATTERN | -f FILE][FILE...]
-e PATTERN, --regexp=PATTERNUse PATTERN as the pattern; useful toprotect patterns beginning with -.
3 dragon March 31, 2009 at 11:26 pm
Hi:
FYI, tip 14 will be2:38:3on Ubuntu system. (including the \n character I guess
4 Ramesh March 31, 2009 at 11:44 pm
Dragon,
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7577http://thisblog.runsfreesoftware.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7605http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7708http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7711http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7577http://thisblog.runsfreesoftware.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7605http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7708http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-7711 -
7/31/2019 Linux Set Date
71/101
Thanks for pointing it out. Ive corrected it.
5Francesco Talamona April 26, 2009 at 2:48 am
I find very useful the following command, when you have to dealwith a very lengthy configuration file full of comments:
grep -v -E ^\#|^$ /etc/squid/squid.conf
It skips every line beginning with an hash (#) or empty, so youcan see at a glance the 15 lines edited out of a +4400 lines textfile.
BTW interesting topics, great posts
6 albar May 7, 2009 at 7:51 pm
help mehow to bzgrep : ^C02but ^C is count as one special character,in this word:
data1^C02data2
thanks
7 Ramesh Natarajan May 8, 2009 at 5:51 pm
@Francesco Talamona,
Thanks a lot for sharing your grep command example. Yes. allthose empty lines and comment lines can get very annoying when
you do grep. So, it is an excellent idea to hide them in the grepoutput with your examples.
8 sasikala May 11, 2009 at 9:41 pm
@albar,
try like this
grep \^C02
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9103http://www.know.eu/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9737http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9807http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10078http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9103http://www.know.eu/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9737http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-9807http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10078 -
7/31/2019 Linux Set Date
72/101
9 albar May 12, 2009 at 1:18 am
@sasikala ,i do have try that too, but still got nothing,
but it works when and C count as two character
thanks
10 SathiyaMoorthy May 12, 2009 at 4:33 am
@albar
You should type ^C as ctrl-v + ctrl-c in grep as single character as$ grep ^C02 file
Dont escape, dont type it as ^ C as two characters. Hope thishelps.
11 albar May 12, 2009 at 8:59 pm
@sathiya,
god bless u allit works thanks
12 Manish Patel May 21, 2009 at 7:00 pm
Hi
I am trying to exclude the last word of all the line like sync.php,uploads.php, backup.php
File text include as below
/usr/home/htdocs/drag-and-drop/htdocs.php/usr/home//htdocs/sms/publish/pages/sync.php/usr/home/htdocs/track/backup.php/usr/home/htdocs/smstest/smstest.php/usr/home/htdocs/uploads.php
/usr/home/htdocs/017/backup.php
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10095http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10109http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10159http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10582http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10095http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10109http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10159http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10582 -
7/31/2019 Linux Set Date
73/101
How can I achieve that using grep or sed or awk
Also how I can use * wildcard in sed command like to replace*.php to *.txt or any other extension.
Thank you in advance.
Manish
13 Francesco Talamona May 21, 2009 at 10:36 pm
Are you restricted to sed or awk?
1)dirname /usr/home/htdocs/drag-and-drop/htdocs.php/usr/home/htdocs/drag-and-drop
2)rename does what you want
14 Manish Patel May 24, 2009 at 6:55 pm
Hi,
Those lines are the contents of the text file and I dont want tochange the actual directory or the file on server. I want to changethe contents of the file where all file file names ending at the lineshould be removed. So the final file contents should look like this
cat filecontenet.txt
/usr/home/htdocs/drag-and-drop//usr/home//htdocs/sms/publish/pages//usr/home/htdocs/track//usr/home/htdocs/smstest//usr/home/htdocs//usr/home/htdocs/
I think rename would not help here in editing file contents.
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10586http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10707http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10586http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10707 -
7/31/2019 Linux Set Date
74/101
Thank youManish
15SathiyaMoorthy May 24, 2009 at 11:43 pm
rev filecontenet.txt | cut -d/ -f2- | rev
rev filecontenet.txt > reverses the file and pipes to cut command.cut -d/ -f2- > cuts off the first field ( cuts off last field, as it isreversed ).rev > prints the output given order.
16 P0B0T May 26, 2009 at 11:36 pm
Manish,
I believe youre looking for the following
sed -e s/.php$// filecontenet.txt
17 P0B0T May 26, 2009 at 11:39 pm
Sorry, didnt read your requirement carefully.
Try this:
sed -e s/\/[^/]*.php$/\// filecontenet.txt
18 Manish Patel June 5, 2009 at 5:31 pm
Hi
Thank you to Sathiya Moorthy and P0B0T.
Both solution worked very nicely for me.
P0B0T can you explain how your command works for eachdefined option s/\/[^/]*.php$/\//
Thank youManish
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10720http://www.thegeekstuff.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10876http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10877http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11227http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10720http://www.thegeekstuff.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10876http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-10877http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11227 -
7/31/2019 Linux Set Date
75/101
19 mano June 10, 2009 at 3:00 am
The above info on grep is really great. I want to search for astring in all the files in the directory and add a $ symbol at the
start of the searched line and save in the same file.
20SathiyaMoorthy June 18, 2009 at 10:49 pm
@manoMore than using grep for this requirement, you can use sed whichis:sed -i s/.*abc.*/$&/ *
-i : edit the input file.s/// : substitute the matched pattern with the replacement string./.*abc.*/ : match the string abc/$&/ : Replace with $ followed by matched string.* : all the files in the current directory.
This is one way of satisfying your requirement, there may beother efficient ways.
Hope this helps.
21 mano June 19, 2009 at 12:17 am
Hi SathiaMoorthy, Thank u so much. it works fine. If I need tosearch for files in all subdirectories, how should this sedcommand modified?
Thanks in advance.
mano
22SathiyaMoorthy June 27, 2009 at 12:05 am
@manoModification in sed command is not needed.
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11335http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11658http://www.thegeekstuff.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11660http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11995http://www.thegeekstuff.com/tag/vi-vim-tips-and-tricks/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11335http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11658http://www.thegeekstuff.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11660http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-11995http://www.thegeekstuff.com/tag/vi-vim-tips-and-tricks/ -
7/31/2019 Linux Set Date
76/101
To search for all files in the subdirectory.find . -type f
Execute the command on all those files with -exec.
find . -type f -exec sed -i s/.*abc.*/#&/ {} \;
But think twice before executing this command, because it willrecursively edit all the files. Taking backup before executing thiscommand is wise.
Refer the earlier article linux find command examples.
23 Vidya July 1, 2009 at 2:59 am
Hi,
I want to grep next 3 words in a line from the matching criteriaword..like if the line is
This is -g gateway -e enterprise -s server
Then I want to grep -g gateway -e enterprise from the line
Can you please help me in this case.Here gateway and enterprise value can be anything so need togrep next 3 words starting form -g
24 SathiyaMoorthy July 1, 2009 at 5:58 am
@Vidhya
$ grep -o -E -g \w+ -e \w+ FILENAME-g gateway -e enterprise
Explanation of the above command.,
-o : only matching ( point 13. )-E : extended regexp
http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-12139http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-12147http://www.thegeekstuff.com/2009/03/15-practical-linux-find-command-examples/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-12139http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-12147 -
7/31/2019 Linux Set Date
77/101
-
7/31/2019 Linux Set Date
78/101
$ grep "not.*summer" file1line2: This is not summer.
$ grep "not" file1 | grep "summer"
line2: This is not summer.29 learner October 7, 2009 at 10:56 pm
@SathiyaMoorthy
Thank You for your very quick reply.
My question was not piping and hard coding every string , as i
mentioned multiple strings, i was looking for something in likesofgrep -F string1string2string3string4..stringn filename
which returns single occurrence of something like either string1,string2,.. stringn or all .., what i wanted was only string1 andstring2 and . stringn begin returned.[please note that i will be provided with strings as newlineseparated strings ,which i don't want to parse again and i haveconstraint of using grep only]
Thank You.
30 Ashish December 1, 2009 at 4:07 pm
Hi,
I need to sthing like thisI have a file containing 400 domainId values seprated by new lineex. domain.txtdomain1
domain2domain3
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-18914http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-24442http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-18914http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-24442 -
7/31/2019 Linux Set Date
79/101
I have a script that takes each domain and calls an api that returnsme an xml.like this for each domainval1domain1val2val3val4XXXval1
now i want to spit out the domain name in a file that does not
matches domainid value XXX.
how can i do it using grepTIA
31 Ashish December 1, 2009 at 4:16 pm
Hi,
I need to sthing like thisI have a file containing 400 domainId values seprated by new lineex. domain.txtdomain1domain2domain3
I have a script that takes each domain and calls an api that returns
me an xml.like this for each domain
val1domain1val2val3val4
XXXval1
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-24445http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-24445 -
7/31/2019 Linux Set Date
80/101
now i want to spit out the domain name in a file that does notmatches domainid value XXX.
how can i do it using grep
TIA
32 Varun December 17, 2009 at 7:16 am
Hi,The options mentioned in point 6 for displaying the context withA, B, & C does not seem to work on Solaris 10 with both grep &egrep
Is there a version of this grep available for Solaris?
Thank you,Varun.
33 Jawn Hewz December 21, 2009 at 7:54 pm
Does the -b (byte offset) work when greping binary files? I do not
get an offset returned when I grep a binary file, but I do whenusing a text file. I am using grep under Cygwin.
34fety January 11, 2010 at 3:32 am
thanks very much for this tutorial. it is very helpful..
35eMancu January 24, 2010 at 12:49 pm
Awsome tutorial!Im reading all your blog, its amazing!
36 Raghu Baba January 30, 2010 at 4:44 am
Hai.. I want to Parse my file .. Word to Excel .. so tell me somegrep & cut commands
37 Jeff Floyd February 1, 2010 at 6:54 pm
http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-26475http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-26926http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-29069http://ingafety.wordpress.com/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-30788http://www.elblogolico.com.ar/http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-31545http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-32026http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-26475http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/#comment-26926http://www.thegeekstuff.