Home System Tutorial LINUX Use Linux AWK commands to make data processing more efficient!

Use Linux AWK commands to make data processing more efficient!

Feb 13, 2024 am 08:48 AM
linux linux tutorial linux system linux command shell script embeddedlinux Getting started with linux linux learning

在Linux系统中,我们经常需要对各种不同格式的数据进行处理和分析。这时候,一个简单又强大的工具就派上用场了 —— AWK。AWK是一种文本处理工具,它可以快速地处理文本文件,并且非常适合用于日志分析、数据提取、统计报表等各种任务。在本文中,我们将为您介绍AWK的基本用法和常见应用场景,让您轻松掌握这个数据处理利器。

0、基本用法

awk是一个强大的文本分析工具,简单来说awk就是把文件逐行读入,(空格,制表符)为默认分隔符将每行切片,切开的部分再进行各种分析处理
awk命令格式如下

awk [-F field-separator] 'commands' input-file(s)
Copy after login

[-F 分隔符]是可选的,因为awk使用空格,制表符作为缺省的字段分隔符,因此如果要浏览字段间有空格,制表符的文本,不必指定这个选项,但如果要浏览诸如/etc/passwd文件,此文件各字段以冒号作为分隔符,则必须指明-F选项

echo "this is a test" | awk '{ print $0 }'  
## 输出为  
this is a test
Copy after login

shell读取用户输入的字符串发现|,代表有管道。|左右被理解为简单命令,即前一个(左边)简单命令的标准输出指向后一个(右边)标准命令的标准输入
awk会根据分隔符将行分成若干个字段,为整行,1为第一个字段,$2 为第2个地段,依此类推…
为打印一个字段或所有字段,使用print命令。这是一个awk动作

echo "this is a test" | awk '{ print $1 }'  
## 输出为  
this  
echo "this is a test" | awk '{ print $1, $2 }'  
## 输出为  
this is
Copy after login

/etc/passwd的文件内容如下

root:x:0:0:root:/root:/bin/bash  
bin:x:1:1:bin:/bin:/sbin/nologin  
daemon:x:2:2:daemon:/sbin:/sbin/nologin  
adm:x:3:4:adm:/var/adm:/sbin/nologin  
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
Copy after login

举几个简单的小需求

1、只显示/etc/passwd的账户

awk -F : '{ print $1 }' /etc/passwd  
## 输出为  
root  
bin  
daemon  
adm  
lp
Copy after login
使用Linux AWK命令, 让数据处理更加高效!

2、显示/etc/passwd的第1列和第7列,用逗号分隔显示,所有行开始前添加列名start1,start7,最后一行添加,end1,end7

awk -F ':' 'BEGIN {print "start1,start7"} {print $1 "," $7} END {print "end1,end7"}' /etc/passwd  
## 输出为  
start1,start7  
root,/bin/bash  
bin,/sbin/nologin  
daemon,/sbin/nologin  
adm,/sbin/nologin  
lp,/sbin/nologin  
end1,end7
Copy after login

BEGIN语句在所有文本处理动作执行之前被执行,END在所有文本处理动作执行之后被执行

3、统计/etc/passwd文件中,每行的行号,每行的列数,对应的完整行内容

awk -F : '{ print NR "  " NF "  " $0 }' /etc/passwd  
## 输出为  
1    7   root:x:0:0:root:/root:/bin/bash  
2    7   bin:x:1:1:bin:/bin:/sbin/nologin  
3    7   daemon:x:2:2:daemon:/sbin:/sbin/nologin  
4    7   adm:x:3:4:adm:/var/adm:/sbin/nologin  
5    7   lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
Copy after login

1、支持内置变量

上面示例中NR,和NF其实就是awk的内置变量,一些内置变量如下

变量名 解释
FILENAMEawk浏览的文件名
FS设置输入字段分隔符,等价于命令行-F选项
NF 浏览记录的字段个数
NR 已读的记录数
Copy after login

2、支持函数

输出字符串的长度

awk 'BEGIN { print length("this is a text") }'
Copy after login

## 输出为
14
/etc/passwd的用户名变成大写输出

awk -F ':' '{ print toupper($1) }' /etc/passwd
Copy after login

## 输出为

ROOT  
BIN  
DAEMON  
ADM  
LP
Copy after login

常用函数如下

函数名 作用
toupper(s)返回s的大写
tolower(s) 返回s的小写
length(s) 返回s长度
substr(s,p) 返回字符串s中从p开始的后缀部分
Copy after login

3、支持条件操作,正则表达式匹配

显示/etc/passwd中有daemon的行

awk -F ‘:’ ‘$0 ~ /daemon/’ /etc/passwd
## 输出为

daemon:x:2:2:daemon:/sbin:/sbin/nologin 
awk条件操作符

操作符 描述
if while do/while for break continue
Copy after login

输出第一个字段的第一个字符大于d的行

awk -F ':' '{ if ($1 > "d") { print $1 } else { print "-" } }' /etc/passwd
Copy after login

## 输出为

root  
-  
daemon  
-  
lp
Copy after login
Copy after login

可以把流程控制语句放到一个脚本中,然后调用脚本执行,如test.sh的内容如下

{   
    if ($1 > "d") {  
        print $1   
    } else {  
        print "-"   
    }   
}
Copy after login

用如下方式执行,效果一样

awk -F ':' -f test.sh /etc/passwd
Copy after login

## 输出为

root  
-  
daemon  
-  
lp
Copy after login
Copy after login

5、应用场景

小编用awk进行文本分析比较少,主要用来写脚本
如一个weibo-interface-1.0.jar应用,启动脚本如下

start.sh
nohup java -jar weibo-interface-1.0.jar >out 2>&1 &
Copy after login

关闭脚本如下,kill.sh

kill -9 `jps -l | grep 'weibo-interface-1.0.jar' | awk '{print $1}'`
Copy after login

jps -l的输出如下

70208 com.st.kmp.main.KmpService  
31036 com.st.cis.main.BaiduAnalysisService  
66813 weibo-interface-1.0.jar
Copy after login

还有就是关闭hadoop集群的所有DataNode节点(不知道hadoop的可以认为DataNode是一个集群应用),假如一个个机器jps,查看pid,kill。很麻烦,直接写了一个脚本,依次ssh到各个节点,然后执行如下命令即可

kill `jps | grep 'DataNode' | awk '{print $1}'`
Copy after login

jps的输出为

508 DataNode  
31481 JournalNode  
31973 NodeManager
Copy after login

总的来说,AWK是一个非常强大的数据处理工具。通过灵活的语法和功能,我们可以快速地处理不同格式的数据,并且生成各种形式的报表和统计数据。在本文中,我们介绍了AWK的基本概念、语法和常见应用场景,并且通过实例演示了如何使用AWK处理数据。希望本文能够帮助读者更好地理解AWK,提高数据处理的效率!

The above is the detailed content of Use Linux AWK commands to make data processing more efficient!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

How to install centos How to install centos Apr 14, 2025 pm 09:03 PM

CentOS installation steps: Download the ISO image and burn bootable media; boot and select the installation source; select the language and keyboard layout; configure the network; partition the hard disk; set the system clock; create the root user; select the software package; start the installation; restart and boot from the hard disk after the installation is completed.

Centos options after stopping maintenance Centos options after stopping maintenance Apr 14, 2025 pm 08:51 PM

CentOS has been discontinued, alternatives include: 1. Rocky Linux (best compatibility); 2. AlmaLinux (compatible with CentOS); 3. Ubuntu Server (configuration required); 4. Red Hat Enterprise Linux (commercial version, paid license); 5. Oracle Linux (compatible with CentOS and RHEL). When migrating, considerations are: compatibility, availability, support, cost, and community support.

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

See all articles