`
zhchx0827
  • 浏览: 191283 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Linux Shell脚本——文件处理

 
阅读更多

 

通过man或--help查看相应的参数

grep:在文件中搜索文本
grep pattern filename
echo -e "this is a word\nnext line" | grep word 从stdin中搜索
grep "pattern" file1 file2 file3  搜索多个文件
grep -E "[a-z]+" file  使用正则表达式搜索时,使用E参数,或者使用egrep搜索
grep -o -E "[a-z]+\." filename  用o指定指数出匹配的部分
grep -v "pattern" filename 打印出匹配到的行之外的所有行
grep -c "pattern" filename 文件中匹配到的字符串的行数
grep "pattern" . -R -n  递归搜索目录中的文本-R递归,-n输出行号
grep -i "pattern" 忽略大小写
grep -e "pattern1" -e "pattern2"  匹配多个表达式
grep -f patterfile filename  patterfile定义搜索的字符串
grep "pattern" . -R --include *.txt 只搜索txt文件
grep "pattern" . -R --exclude *.txt 搜索出txt之外的文件


cut按列切分文件
cut -f 1,3 filename 切分文件的第1,3列
cut -f 2 --component filename 切分除第2列之外的列
cut -f 2 -d " " filename 切分第2列,默认通过空格分隔列


sed流编辑器,多用来进行文本替换
sed 's/pattern/replace_string/' filename      替换文本
sed -i 's/pattern/replace_string/' filename   将替换应用于原文件
sed 's/pattern/replace_string/' file1 > file2 替换后的内容从定向到file2
sed 's/pattern/replace_string/g' filename     替换文件中所有的pattern
sed 's/pattern/replace_string/2g' filename    替换第二个pattern开始后的所有字符串
sed 's:pattern:replace_string:2g' filename    同样可以使用:替代/作为定界符
sed '/^$/d' filename   使用/pattern/d移除匹配的行  ^$可以匹配空白行
echo this is an example | sed 's/\w\+/[&]/g' 输出[this] [is] [an] [example] &标记匹配的字符串
echo this is an example | sed 's/\(this\) \(is\)/\2 \1/' 输出is this an example \n代表匹配到的第n个子串,\(pattern\)匹配字串
echo hello world | sed "s/$text/HELLO/" $text是一个变量,这个时候使用双引号代替单引号
sed 's/pat1/str1/' file | sed 's/pat2/str2/'   通过管道可以指定多个sed
sed 's/pat1/str1/;s/pat2/str2/' file  效果同上


awk用于数据流,可以同时对列和行进行操作

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics