Monday, July 14, 2014

Road to RHCE - Day 5

Day 5

I/O redirection

To redirect  the output of a command to a file

hwclock > [filename]


To redirect the error from a command to a file

hwclok 2> [filename]


To redirect the standard input to a file

cat > [filename] << [eof_string]
blah blah
blah blah
[eof_string]


A sample shell script to create a text file with contents

#!/bin/bash
cat > test1 << END
This is the first line
This is the second line
END


Use of pipe ( | ) symbol

The pipe ( | ) symbol is used to redirect the output of first command as the input of the second.

date | cat > date.out

[! the above command will create the date.out file with the current date as it's content]


Text processing tools

There are many text processing tools in linux, like -

less
head
tail
more
cat
grep
sed
awk
cut
diff
tailf
wc
sort


To display top 'n' number of lines in a file

head -n [filename]


To display bottom 'n' number of lines in a file

tail -n [filename]


To search a string in a file

grep [string] [filename]


sed

The definition of sed is System Editor. It is used to find and replace a string in a file.


To search and replace only the first occurrence of the string of every line temporarily

sed 's/old_value/new_value' [filename]


To search and replace all occurrences of the string temporarily

sed 's/old_value/new_value/g' [filename]


To search and replace all occurrences of the string permanently

sed -i 's/old_value/new_value/g' [filename]


To delete a line (say, 3rd line) using sed

sed -i '3d' [filename]


To extract specific field from a text file

cut -d: -f6 [filename]

[! where : is the delimiter and 6 denotes sixth field to extract]



To find the difference between two files

diff [file1] [file2]


To get the statistics of a text file

wc [filename]

[! this will provide the number lines, characters, words that are present in that file]


To sort the contents of a file

sort [filename]


To find a file

find -name "*.txt"

find /home/ -user testuser

[! this command searches all files owned by testuser under /home]


Executing commands with 'find'

  • Commands must be preceded with either -exec or -ok (-ok prompts before acting on each file).
  • Command must end with ' \;' (a space, a backslash and a semicolon)
  • Can use {} as filename placeholder

find -size +100M -exec mv {} /tmp/ \;

[! the above command will search for any file that is >100MB in the current directory and move all those files to /tmp/]


To create a dummy file of size 1GB

dd if = /dev/null of = [target_filename] bs = 100M count = 10



-- End of Day 5 --

No comments: