在Linux上使用Sed处理文本流
时间:2020-03-21 11:46:38 来源:igfitidea点击:
GNU Sed
我们以以下文件为例:
$cat file.txt one two one two one two one two one two one two one two one two ONE TWO ONE TWO ONE TWO ONE TWO
删除包含特定字符串的行
$sed '/one/d' file.txt ONE TWO ONE TWO ONE TWO ONE TWO
替换每行上字符串的第一次出现
$sed 's/one/ONE/' file.txt ONE two one two one two one two ONE two one two one two one two ONE TWO ONE TWO ONE TWO ONE TWO
替换文件中字符串的特定出现
$sed 's/one/ONE/' file.txt ONE two one two one two one two ONE two one two one two one two ONE TWO ONE TWO ONE TWO ONE TWO
$sed 's/one/ONE/3' file.txt one two one two ONE two one two one two one two ONE two one two ONE TWO ONE TWO ONE TWO ONE TWO
$sed 's/one/ONE/g' file.txt ONE two ONE two ONE two ONE two ONE two ONE two ONE two ONE two ONE TWO ONE TWO ONE TWO ONE TWO
$sed 's/one/ONE/3g' file.txt one two one two ONE two ONE two one two one two ONE two ONE two ONE TWO ONE TWO ONE TWO ONE TWO
使所有字母变为大写
$sed 's/./\U&/g' file.txt ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO ONE TWO
使所有字母变为小写
$sed 's/./\L&/g' file.txt one two one two one two one two one two one two one two one two one two one two one two one two
在每行的开头添加单词
$sed 's/^/START /' file.txt START one two one two one two one two START one two one two one two one two START ONE TWO ONE TWO ONE TWO ONE TWO
在每行末尾添加单词
$sed 's/$/END/' file.txt one two one two one two one two END one two one two one two one two END ONE TWO ONE TWO ONE TWO ONE TWO END
删除所有空行
$sed '/^$/d'
删除所有包含空格和制表符的空行
$sed '/^\s*$/d'
列出当前目录中的所有文件,但不包括某些扩展名
$ls -1 | sed '/csv\|txt\|log/d'
从Unix样式($)转换为DOS样式(\ r)
$sed s/$/"\r"/dosfile.txt > unixfile.txt
从每一行中删除第一个字符
$sed s'/^.//'
从每一行中删除最后一个字符
$sed s'/.$//'
删除所有少于6个字符的行
$sed '/.\{6\}/!d'
用逗号替换换行符
这将循环读取整个文件,然后用逗号替换换行符。
$sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/,/g' file.txt