Jumat, 03 Desember 2010

Sed command linux

sed
(=stream editor) I use sed to filter text files. The pattern to match is typically included between a pair of slashes // and quoted.
For example, to print lines containing the string "1024", I may use:
cat filename | sed -n '/1024/p'
Here, sed filters the output from the cat command. The option "-n" tells sed to block all the incoming lines but those explicitly matching my expression.  The sed action on a match is "p"= print.
Another example, this time for deleting selected lines:

cat filename | sed '/.*o$/d' > new_file

In this example, lines ending the an "o" will be deleted. I used a regular expression for matching any string followed by an "o" and the end of the line. The output (i.e., all lines but those ending with "d") is directed to new_file.
Another example. To search and replace, I use the sed 's' action, which comes in front of two expressions:

cat filename | sed 's/string_old/string_new/' > newfile

A shorter form for the last command is:
sed 's/string_old/string_new/' filename > newfile
To insert a text from a text file into an html file, I may use a script containing:
sed '/text_which_is_a_placeholder_in__my_html_file/r text_file_to_insert.txt' index_master_file.html > index.htmll

sed G myfile.txt > newfile.txt
In the above example using the sed command with G would double space the file myfile.txt and output the results to the newfile.txt.
sed = myfile.txt | sed 'N;s/\n/\. /'
The above example will use the sed command to output each of the lines in myfile.txt with the line number followed by a period and a space before each line. As done with the first example the output could be redirected to another file using > and the file name.
sed 's/test/example/g' myfile.txt > newfile.txt
Opens the file myfile.txt and searches for the word "test" and replaces every occurrence with the word "example".
sed -n '$=' myfile.txt
Above this command count the number of lines in the myfile.txt and output the results.


Tidak ada komentar:

Posting Komentar

Laman