sed命令小记

sed  将内容一行行加载到内存空间,处理,然后再打印到屏幕; 默认是不修改源文件的
sed -niefr 'line action 修饰符' file ...
    -n 静默模式 , 只打印处理的行
    -i 直接修改源文件
    -e script -e script 
    -f sed_script 
    -r  使用egrep
line 
    1,100
    5 
    $
    $-1
    1,+21行开始,向后的2行,即1~3/regexp/, /regexp/   
action 
    d   
    p   
    a \str   
    i \str   
    r file 
    w file 
    s/regexp/str/
        sed '1,$s/oot/OOT/' file  如果行范围是1,$即全文,则可省略 sed 's@oot@OOT@' file 
        &  引用匹配到的整个字符串
        后向引用  \( \)  \1  \2 
修饰符  gi

示例:

sed '3,$d' file   删除
sed '1,+2d' file 
sed '/oot/d' file   删除匹配到的行
sed '/^\//d' file   删除以 / 开头的行

sed -n '/^\//p' file  打印

sed '/^\//a \# hello world\n# hello linux' file  追加

sed '$r /etc/issue' file   读入
sed '1,2r /etc/issue' file 

sed '/oot/w /tmp/oot.txt' file   写出

sed 's@l..e@&r@g' file 
sed 's@\(l..e\)@\1r@g' file 
history | sed 's#^[[:space:]]*##g' | cut -d' ' -f1

练习:

1. 给定一个路径,取出父目录?
    echo /etc/profile.d/run.sh | sed -r 's@(/.*/)[a-z._0-9A-Z]+/?@\1@'
    echo /etc/profile.d/run_sh | sed -r 's@(/.*/)([a-z._0-9A-Z]+)/?@\2@'
    dirname   basename  

2. 删除/etc/grub.conf文件中行首的空白符
    sed -r 's@^[[:space:]]+@@g' sedfile

3. 替换/etc/inittab文件中"id:3:initdefault:"一行中的数字为5
    sed -r 's@(id:)[0-9](:[a-zA-Z]+:)@\15\2@' sedfile

4. 删除/etc/inittab文件中的空白行

5. 删除/etc/inittab文件中开头的#号

6. 删除某文件中开头的#号及后面的空白字符,但要求#号后面必须有空白字符

7. 匹配某文件中以空白字符后跟#的行, 并删除开头的空白符及# ?
本作品采用《CC 协议》,转载必须注明作者和本文链接
六月的风
Junwind
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!