Linux awk 命令简单使用

Linux awk About 2,251 words

说明

awkLinux下文本处理(文本编辑命令是sed)的实用命令之一。

常用命令

文本:

{"phone":"12345678901","status":1, "time":1}
  • $0与$n

$0是输出整段文本,$1$2$3...是输出分割后的第1、2、3个字段

  • 自定义分隔符

:为分隔符,使用-F指定:

awk -F':' '{print $1}' test.txt

输出:

{"phone"
  • 添加自定义首尾行

BEGINEND

awk 'BEGIN{print "This is the first row"} {print $0} END{print "This is the end row"}' test.txt

输出:

This is the first row
{"phone":"12345678901","status":1, "time":1}
This is the end row
  • 提取phone字段的值

两次awk:第一次以"phone":"分割,得到12345678901","status":1, "time":1}。再以"分割,取得12345678901

问:为什么awk两次而不是直接一次取第4个字段awk -F'"' '{print $4}' test.txt
答:json串可能有多条,并且可能出现的位置随机,可能在status字段后。

awk -F'"phone":"' '{print $2}' test.txt | awk -F'"' '{print $1}'

输出:

12345678901

帮助文档

Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
Usage: awk [POSIX or GNU style options] [--] 'program' file ...
POSIX options:          GNU long options:
        -f progfile             --file=progfile
        -F fs                   --field-separator=fs
        -v var=val              --assign=var=val
        -m[fr] val
        -O                      --optimize
        -W compat               --compat
        -W copyleft             --copyleft
        -W copyright            --copyright
        -W dump-variables[=file]        --dump-variables[=file]
        -W exec=file            --exec=file
        -W gen-po               --gen-po
        -W help                 --help
        -W lint[=fatal]         --lint[=fatal]
        -W lint-old             --lint-old
        -W non-decimal-data     --non-decimal-data
        -W profile[=file]       --profile[=file]
        -W posix                --posix
        -W re-interval          --re-interval
        -W source=program-text  --source=program-text
        -W traditional          --traditional
        -W usage                --usage
        -W use-lc-numeric       --use-lc-numeric
        -W version              --version

To report bugs, see node `Bugs' in `gawk.info', which is
section `Reporting Problems and Bugs' in the printed version.

gawk is a pattern scanning and processing language.
By default it reads standard input and writes standard output.

Examples:
        gawk '{ sum += $1 }; END { print sum }' file
        gawk -F: '{ print $1 }' /etc/passwd
Views: 2,394 · Posted: 2019-08-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh