Linux 技巧

Posted by ZYT on March 6, 2019

1. vim 黏贴代码格式混乱

:set paste

2. crontab 修改默认编辑器

> select-editor

3. awk

# 输出特定列
$ awk '{print $1, $4}' test.txt

# 过滤记录
$ awk '$3==0 && $4=="LISTEN" {print $2} ' test.txt

# 保留表头
$ awk '$3==0 && $4=="LISTEN" || NR==1 ' test.txt

# 输出行号
$ awk '$3==0 && $6=="ESTABLISHED" || NR==1 {printf "%02s %s %-20s %-20s %s\n",NR, FNR, $4,$5,$6}' test.txt

# 字符串匹配
$ awk '$6 ~ /FIN|TIME/ || NR==1 {print NR,$4,$5,$6}' test.txt

# 从file文件中找出长度大于80的行
$ awk 'length>80' file

awk 脚本

# 查看数据
$ cat score.txt
Marry   2143 78 84 77
Jack    2321 66 78 45
Tom     2122 48 77 71
Mike    2537 87 97 95
Bob     2415 40 57 62

# 查看脚本
$ cat cal.awk
#!/bin/awk -f
#运行前
BEGIN {
    math = 0
    english = 0
    computer = 0
 
    printf "NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL\n"
    printf "---------------------------------------------\n"
}
#运行中
{
    math+=$3
    english+=$4
    computer+=$5
    printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5
}
#运行后
END {
    printf "---------------------------------------------\n"
    printf "  TOTAL:%10d %8d %8d \n", math, english, computer
    printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR
}

# 执行并查看结果
$ awk -f cal.awk score.txt
NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL
---------------------------------------------
Marry  2143     78       84       77      239
Jack   2321     66       78       45      189
Tom    2122     48       77       71      196
Mike   2537     87       97       95      279
Bob    2415     40       57       62      159
---------------------------------------------
  TOTAL:       319      393      350
AVERAGE:     63.80    78.60    70.00

4. sed

$ cat pets.txt
This is my cat
  my cat's name is betty
This is my dog
  my dog's name is frank
This is my fish
  my fish's name is george
This is my goat
  my goat's name is adam

# 将其中的 my 字符串替换为 test ,结果仅输出到控制台
$ sed "s/my/test/g" pets.txt

# 将内容重定向到其他文件
$ sed "s/my/test/g" pets.txt > test_pets.txt

# 直接修改文件内容
$ sed -i "s/my/test/g" pets.txt

# 在每一行最前面加点东西
$ sed 's/^/#/g' pets.txt
#This is my cat
#  my cat's name is betty
#This is my dog
#  my dog's name is frank
#This is my fish
#  my fish's name is george
#This is my goat
#  my goat's name is adam

# 在每一行最后面加点东西
$ sed 's/$/ --- /g' pets.txt
This is my cat ---
  my cat's name is betty ---
This is my dog ---
  my dog's name is frank ---
This is my fish ---
  my fish's name is george ---
This is my goat ---
  my goat's name is adam ---

正则表达式的一些最基本的东西:

  • ^ 表示一行的开头。如:/^#/ 以#开头的匹配。
  • $ 表示一行的结尾。如:/}$/ 以}结尾的匹配。
  • \< 表示词首。 如:\<abc 表示以 abc 为首的詞。
  • \> 表示词尾。 如:abc\> 表示以 abc 結尾的詞。
  • . 表示任何单个字符。
  • * 表示某个字符出现了0次或多次。
  • [ ] 字符集合。 如:[abc] 表示匹配a或b或c,还有 [a-zA-Z] 表示匹配所有的26个字符。如果其中有^表示反,如 [^a] 表示非a的字符

5. Linux 相关设置

5.1 关闭系统警告

$ vim /etc/inputrc
#set bell style none 找到并去掉 #

5.2 配置 Github

$ git config --global credential.helper store