Wednesday, July 20, 2011

sed linux/mac

windows下,每一行的结尾是\n\r,而在linux下文件的结尾是\n,那么你在windows下编辑过的文件在linux下打开看的时候每一行的结尾就会多出来一个字符\r, 用cat -A urfile时你可以看到这个\r字符被显示为^M,这时候只需要删除这个字符就可以了。可以使用命令

Linux

sed -i 's/\r$//' urfile

Mac:

sed 's/\r$//' urfile > newfile
or
sed -i '' 's/\r$//' urfile


Removing one (or several) line (s) of a file


Syntax:


sed '{[/]<n>|<string>|<regex>[/]}d' <fileName>
sed '{[/]<adr1>[,<adr2>][/]d' <fileName>
  • /.../=delimiters
  • n = line number
  • string = string found in in line
  • regex = regular expression corresponding to the searched pattern
  • addr = address of a line (number or pattern )
  • d = delete


Examples

Remove the 3rd line:

sed '3d' fileName.txt


Removal of the line containing the string "awk":

sed '/awk/d' filename.txt


Remove the last line:

sed '$d' filename.txt



Remove all empty lines:

sed '/^$/d' filename.txt
sed '/./!d' filename.txt


Remove line "matched" by a regular expression (by eliminating one containing digital characters (at least 1 digit) located at the end of the line).

sed '/[0-9/][0-9]*$/d' filename.txt


Removing the interval between lines 7 and 9.

sed '7,9d' filename.txt 


Same operation but replacing the address by "parameters".

sed '/-Start/,/-End/d' filename.txt



The above examples are only change at the display of the file (stdout1= screen).

For permanent changes to the old versions (<4) use a temporary file for GNU sed use the "-i[suffix]":

sed -i".bak" '3d' filename.txt

source: http://en.kioskea.net/faq/1451-sed-delete-one-or-more-lines-from-a-file

No comments:

Post a Comment