处理文件
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}