sed stands for stream editor.
sed is mainly used for finding and replacing patterns, searching, inserting, deleting
etc. sed reads from input stream line by line. It also supports regular expression for
filtering the inputs.
Below are few best questions on sed
Q. How to print contents of a file?
sed -n 'p' [fileName]
Q. Print the lines which contain the word "pattern"?
sed -n '/pattern/p' [fileName]
Q. Print the lines which does not contain the word "pattern"?
sed -n '/pattern/!p' file [fileName]
Q. Search lines which contain the word "pattern" and print 5 lines after this word?
sed -n '/pattern/, +5p' [fileName]
Q. Delete first line and output all other lines?
sed '1d' file [fileName]
Q. Delete last line of a file and output all other lines?
sed '$d' file [fileName]
Q. Delete first line and update the same in file ?
sed -i -n '1d' [fileName]
Q. Print first 5 lines of a file?
sed -n '1,5p' [fileName]
Q. Print line 15th to end of a file?
sed -n '15,$p' [fileName]
Q. Print number of lines of a file?
sed -n '$=' [fileName]
Q. Write line number before each line of a file?
sed = [fileName] | sed 'N;s/\n/\ /'
Q. Print line number 5th, 10th, 15th, 20th and so on?
sed -n '0~5 p' [fileName]
Q. Print total number of lines that contains the word "pattern"?
sed -n '/pattern/p' [fileName]|sed -n '$='
Q. Print lines between the words "pattern1" and "pattern2"?
sed -n '/pattern1/,/pattern2/ p' [fileName]
Q. Remove leading spaces in the beginning of lines and then print the lines?
sed 's/^[ ]*//' [fileName]
Q. Replace and print all the occurrences of word "pattern1" with "pattern2"?
sed 's/pattern1/pattern2/g' [fileName]
Q. Replace all the occurrences of word "pattern1", irrespective of upper or lower case letter,
with "pattern2" and print the lines?
sed 's/pattern1/pattern2/ig' [fileName]
Q. Remove all the spaces and print the lines?
sed 's/\ //g' [fileName]
Q. Remove blank lines of a file and then print?
sed '/^$/d' [fileName]
Q. Print lines which does not start with #?
sed -n '/^#/!p' [fileName]
Q. Print lines which does not start with "#" and lines which are not blank?
sed -e '/^#/d' -e '/^$/d' [fileName]
Q. Find the word "pattern" and add a line before it "#Below is the pattern found"?
sed '/pattern/ i "#Below is the pattern found"' [fileName]
Q. Find the word "pattern" and add a line after it "#Above is the pattern found"?
sed '/pattern/ a "#Above is the pattern found"' [fileName]
Q. Print lines which contains atleast 1 numeric digit?
sed -n '/[[:digit:]]/p' [fileName]
Q. Replace the characters D with S, @ with & and B with A?
sed 'y/D@B/S&A' [fileName]