提交 f93c22be 编写于 作者: F feilong

增加awk

上级 3b632c35
1. hello world
2. wold hello
3. nothing is important
4. i like movie movie
hello world
wold hello
nothing is important
i like movie movie
\ No newline at end of file
{
"node_id": "gml-d6688990de744b7fa45a0b473dbeff83",
"keywords": [],
"keywords_must": ["Linux命令"],
"keywords_forbid": [],
"children": [],
"export": [
"exercise_01.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"author": "幻灰龙",
"source": "exercise_01.md",
"notebook_enable": false,
"depends": []
}
\ No newline at end of file
# 实用Linux命令掌握20%:awk
Linux 命令很多,掌握最实用的一批命令,对于每个实用命令,又只需掌握20%最高频操作。
**本节知识**
假设文件`1.txt`的文本如下(可以利用`touch`命令和`vi`命令组合创建):
```bash
1. hello world
2. wold hello
3. nothing is important
4. i like movie movie
hello world
wold hello
nothing is important
i like movie movie
```
`awk` 命令可以用来过滤文本,简单理解就是对文本的每行执行命令`awk`指定的脚本,它的基本命令格式如下:
```bash
awk 'BEGIN{ commands } pattern{ commands } END{ commands }' file
```
其中:
* `'BEGIN{ commands }` 指定最开始执行的脚本
* `pattern{ commands }` 对文件的每一行遍历,判断是否满足`pattern`的模式,如果满足则执行脚本
* `END{ commands }` 指定最后执行的脚本
这里是最常用的几个操作例子:
* 打印“开始”,打印每行,打印“结束”: `awk 'BEGIN{ print "开始" } { print } END{ print "结束" }' 1.txt`
* 打印每行的行号:`awk '{print NR}' 1.txt`
* 打印每行的文本:`awk '{print $0}' 1.txt`
* 打印每行的第1列(默认用空格分离):`awk '{print $1}' 1.txt`
* 打印每行的最后1列(默认用空格分离):`awk '{print $NF}' 1.txt`
* 打印每行的倒数第2列(默认用空格分离):`awk '{print $(NF-1)}' 1.txt`
* 打印每行,并为每行带上行号:`awk '{print NR":",$0}' 1.txt`
* 打印含有序号的行:`awk '/\d./ {print}' 1.txt`
**本节任务**
1. 请在[线上Linux环境](https://edu.csdn.net/lab/36675?targetLesson=2692)里练习上述`grep`命令。
2. 以下对命令`grep`描述错误的是?
## 答案
```bash
打印倒数第2列的命令是:
`awk '{print (NF-1)}' 1.txt`
```
## 选项
### A
```bash
打印倒数第2列的命令是:
`awk '{print $(NF-1)}' 1.txt`
```
### B
```bash
`BEGIN{commands}`是可以省略的
`END{commands}`是可以省略的
```
### C
```bash
打印倒数第4列的命令是:
`awk '{print $4}' 1.txt`
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册