shell脚本分行、分词
来源:互联网 发布:网络挂号厦门长庚医院 编辑:程序博客网 时间:2024/05/23 13:05
利用shell脚本可以很容易的对文本文件进行分行、分词。
首先得先了解一个特殊的环境变量IFS(internal field separator);
这个环境变量定义了bash shell用作字符分割符的一系列字符。在默认的情况下,IFS以以下字符作为字段分割符:
空格
制表符
换行符
bash shell遇到以上任一字符,则认为遇到一个新的字符段。有时为了方便处理文件,我们需要一个或者更多个字段分割符,我们可以利用以下语句更改IFS;
IFS=$':' #一个分割符时,将会以冒号为分割符IFS=$'\n:;' #多个分割符,将会以回车、冒号、分号作为分割符
为了防止在脚本中定义了新的字段分割符,而在脚本结束后忘记恢复IFS默认值,在写shell脚本时可以这样写:
IFS_OLD=$IFS #保存默认IFS值IFS=$'\n' #自定义的分割符##<使用新的IFS的脚本代码>##IFS=$IFS_OLD #脚本结束后,恢复默认值
具体的代码:
处理文件
vim test_file
this is IFS test file
changing the IFS calue
hello world
1:shell脚本分行代码
vim ifs_test.sh
#!/bin/shFILE=test_file #文件名字需要改为要处理的文件名IFS_OLD=$IFSIFS=$'\n'for line in `cat $FILE`do echo $linedoneIFS=$IFS_OLD
代码很简单,以回车为字段分割符去处理文件。
2:脚本分词
vim ifs_test.sh
#!/bin/shFILE=test_file #文件名字需要改为要处理的文件名IFS_OLD=$IFSIFS=$'\n'for line in `cat $FILE`do echo $line IFS=$' ' for word in `echo $line` do echo $word donedoneIFS=$IFS_OLD
处理结果:
chmod u+x ifs_test.sh./ifs_test.sh
this is IFS test file
this
is
IFS
test
file
changing the IFS calue
changing
the
IFS
calue
hello world
hello
world
测试实例通过,利用IFS这个环境变量可以很方便的处理文件。比用c语言编程处理文件放便多了。
0 0
- shell脚本分行、分词
- python3结巴分词分行拆分统计词频
- linux shell脚本如何将文本内容按空格分行、如何使用timit原始corpus制作wav的scp文件
- shell脚本
- shell脚本
- shell脚本
- shell脚本
- shell脚本
- shell脚本
- shell脚本
- shell 脚本
- SHELL 脚本
- shell脚本
- shell脚本
- shell 脚本
- shell脚本
- shell脚本
- shell脚本
- windows 清理c盘
- Android AudioManager获取媒体焦点
- RubyCritic:一款不错的检测代码质量工具
- 1948-2006:哈佛大学地理系的灭亡与地理学的重生
- Pitfall in node crypto and base64 encoding
- shell脚本分行、分词
- linux中为什么要有分段和分页机制
- fir.im Weekly - 一切从知识重构开始
- theano 0.8与pydot、graphziv的冲突解决
- 20160229系统集成项目管理工程师(test1)
- Test
- gvim中文乱码解决方案
- eclipse下NDK生成.SO文件
- Spring MVC and Maven – first project: Hello world! Basic template