单行bash命令
2016-07-23 02:13
441 查看
处理文件
1.清空文件
> file
这个跟
echo "some thing" > file一个道理。
2.往文件中添加字符串
echo "some thing" >> file
>>和
>的区别就是一个是添加一个是覆盖。
3.从文件中读取一行
read -r line < file
read命令将file中的第一行读出,保存在line变量中。
-r的作用是将反斜杠
\原样输出。
read命令暗地里还做了一件事是,将一行字符串的行首行尾“清理干净”,比如将space, tab, and newline这些东西干掉。而这些东西是bash中的IFS(internal field saperator)指定的。如果想保留行首行尾这些特殊字符,使用
IFS= read -r line < file
从文件中读出一行还可以这么干:
line=$(head -1 file)
或者
line=`head -1 file`
4.一行一行地读取文件
while read -r line; do # do something with $line done < file
或者
cat file | while IFS= read -r line; do # do something with $line done
5.随机读取一行
read -r line < <(shuf file)
shuf是gun的一个工具,可以达到乱排的效果。
<(shuf file)形成了一个临时文件
/dev/fd/n。
上面命令相当于:
read -r line < /dev/fd/n
还可以使用
sort -r达到乱排效果。
read -r line < <(sort -R file)
或者
line=${sort -R file | head -1}
6.读取每一行的前三列
$ while read -r field1 field2 field3 throwaway; do # do something with $field1, $field2, and $field3 done < file
每行的列由IFS分割而成。
7.统计文件行数、单词书和字节数
用wc
cat file-with-5-lines x 1 x 2 x 3 x 4 x 5 wc file-with-5-lines 5 10 20 file-with-5-lines
字符串处理
1.生成字符序列
echo {a..z} echo {1..10}
2.连接两个字符串
x=-n y=" foo" echo $x$y
output:
foo
x=-n y=" foo" echo "$x$y"
output
-n foo
3.分割字符串
IFS=- read -ra x y z <<< “foo-bar-baz”那么x, y, z分别是foo, bar, baz。
IFS=- read -ra parts <<< “foo-bar-baz”
放进了数组parts中,可通过(parts[0])或者(parts[@])获取数组元素。
4.字符串长度
echo ${#str}相关文章推荐
- 一波实用的Bash Shell整理
- bash脚本输入密码不回显问题的解决方法
- bash 编程中循环语句用法
- Linux BASH多进程并行处理的方法实现
- BASH 学习笔记小结
- 写出健壮Bash Shell脚本的一些技巧总结
- Bash Shell中忽略大小写的设置方法
- Linux bash Shell中的变量类型详解
- Linux系统中bash shell编程的10个基础问题讲解
- linux BASH shell下设置字体及背景颜色
- bash获取当前路径示例
- Bash Shell 注释多行的几种方法
- linux bash字符串处理大全
- 让代码整洁、过程清晰的BASH Shell编程技巧
- 使用Bash Shell获取文件名和目录名的简单方法
- Bash Shell脚本学习小结
- bash批量修改文件名称的方法小结(增加,去除,修改后缀)
- Bash Shell中Shift用法分享
- bash 循环中变量作用范围的问题分析
- 在Debian系的Linux中检查软件包是否被安装的方法