Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Created September 7, 2018 01:57
Show Gist options
  • Save ibreathebsb/cf138885f91bc540cef3f11e47911141 to your computer and use it in GitHub Desktop.
Save ibreathebsb/cf138885f91bc540cef3f11e47911141 to your computer and use it in GitHub Desktop.

awk

行内文本编辑,行内默认以空格或者Tab分割

awk 'condition1 {command1} condition2 {command2} ...'

# awk命令中的变量使用时不需要加$符号
# NF 当前行的列数
# NR 当前的行数
# FS 分隔符
# $0 ~ $n: $0表示这一行, $1...表示这一行的第n项

# 只列出权限和文件名

root@debian-gnu-linux-vm:~# ls -al | awk '{printf "%s\t%s\n",$1,$9}'
total	
drwx------	.
drwxr-xr-x	..
-rw-------	.bash_history
-rw-r--r--	.bashrc
drwx------	.cache
-rw-r--r--	.profile
-rw-------	.rnd

# 注意到上面多了个total 怎么把它去掉?
# 加一个条件判断 如果是第一行,啥都不做

root@debian-gnu-linux-vm:~# ls -al | awk 'NR==1 {} NR>=2 {printf "%s\t%s\n",$1,$9}'
drwx------	.
drwxr-xr-x	..
-rw-------	.bash_history
-rw-r--r--	.bashrc
drwx------	.cache
-rw-r--r--	.profile
-rw-------	.rnd

# 计算total

# Name    1st     2nd     3th
# VBird   23000   24000   25000
# DMTsai  21000   20000   23000
# Bird2   43000   42000   41000

root@debian-gnu-linux-vm:~# cat new | awk 'NR==1 {printf "%s\t%s\t%s\t%s\t%s\n",$1,$2,$3,$4,"Total"} \
> NR>=2 {printf "%s\t%s\t%s\t%s\t%s\n",$1,$2,$3,$4,$1+$2+$3+$4}'
Name	1st	2nd	3th	Total
VBird	23000	24000	25000	72000
DMTsai	21000	20000	23000	64000
Bird2	43000	42000	41000	126000


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment