关于一般文本的增删改查,我们可以看看:https://www.yuque.com/mugpeng/linux/plfwh1
但这些主要是用来处理列表上的操作。(其实够强大它们也是可以的)

就像R 中的dplyr 和stringr 一样,是比较专门的用来两种操作的方式。

这里学习一下linux 字符串的一些操作,参考:https://www.cnblogs.com/gaochsh/p/6901809.html

1)expr 命令

expr 不仅可以用来进行简单数学运算,还可以用来计算字符串长度、抓取字符串、抓取第一个字符数字串出现的位置:

  1. # 长度
  2. expr length "this is a test" # mac 中无法使用
  3. 14
  4. > expr substr this is a test 3 5
  5. is is
  6. > expr index "sarasara" a
  7. 2

2)利用变量的#、%、/ 查看长度、替换、删除

  1. a="this is a test"
  2. echo ${#a} # 计算字符a 的长度
  3. 14
  4. ${a#*is} # 从左最短删除任意出现is 的字符
  5. $ echo ${a#*is}
  6. is a test
  7. ${a##*is} # 从左最长删除任意出现is 的字符
  8. ${a##*is}
  9. a test
  10. ${a%is*} # 从右最长删除任意出现is 的字符
  11. echo ${a%is*}
  12. this
  13. ${a%%is*} # 从右最长删除任意出现is 的字符
  14. echo ${a%%is*}
  15. th
  16. ${a/is/at} # 将从左到右的第一个is 字符替换为at
  17. echo ${a/is/at}
  18. that is a test
  19. ${a/is/IS} # 将所有的is 字符替换为IS
  20. $ echo ${a//is/IS}
  21. thIS IS a test
  22. {a:0:10} # 切片,从0 到10,包头包尾
  23. $echo {a:0:10}
  24. this is a

3)其他截取字符串的方式

  1. # 截取1,8 字符
  2. 1. awk substr()
  3. $ echo this is a test |awk '{print substr($0,1,8)}'
  4. this is
  5. 2. cut -c # 以字符为单位截取
  6. $ echo $a | cut -c1-8
  7. this is