单行bash命令

处理文件

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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值