Sunday, February 1, 2015

sed usage

grep user /etc/passwd ==> this will show the lines contains text "user"
grep ^user /etc/passwd ==> this will show the lines contains and the lines starts with text "user"

Version of grep ==> grep --version

Version of sed ==> sed --version

Cat file in using sed ==> sed 'p' /etc/passwd => each line is printed twice in output
Without duplicate as above ==> sed -n 'p' /etc/passwd
Range of lines say 1 to 5 ==> sed -n '1,5 p' /etc/passwd
Line start with user ==> sed -n ' /^user/ p' /etc/passwd

sed ' /^#/ d'  /etc/ntp.conf ==> will delete lines with # in output
sed ' /^#/ d ; /^$/ d' /etc/ntp.conf ==> This will delete lines with # and empty lines in output.
*Above two commands are not modifying the file but only showing updated output.

Wednesday, September 12, 2012

Redirect Errors and Output to a file


To pass only errors to a file, use below syntax. 

Command 2> err.txt 

For example :

Create a blank directory 
mkdir test1
cd test1

Create some blank files
touch file1
touch file2
touch file3

ls -lrt file*
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file3
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file2
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file1

ls -lrt file5
ls: file5: No such file or directory

Now redirecting error to one file.
ls -lrt file5 2> err.txt

cat err.txt 
ls: file5: No such file or directory

Similarly, this can be used for transferring errors to a file, very popular in shell scripting


some command 2> /dev/null

For transferring error free output use tee, this will insert as well as redirect output to a file.

For example:

cat file* | tee out.txt | cat -n

cat - this will open the file
tee will display and redirect output
cat -n will list the file that were opened during the execution of command.