ack 命令详解

| 选择喜欢的代码风格  

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

ack 命令安装:


-bash/zsh: ack: command not found

#Debian
apt-get install ack

#Ubuntu
apt-get install ack

#Alpine
apk add ack

#Arch Linux
pacman -S ack

#Kali Linux
apt-get install ack

#Fedora
dnf install ack

#OS X
brew install ack

#Raspbian
apt-get install ack

#Docker
docker run cmd.cat/ack ack

-----------------
# ubuntu下要安装 ack-grep,因为在 Debian 中,ack 这个名字被其他的软件占用了。
sudo apt-get install ack-grep

# alpine Linux-apk 软件包管理器 安装 ack
apk install ack

#ack 可以通过 .ackrc 来进行定制.比如下面举例:
# 设置排序
--sort-files

#设置文件过滤
--python
--html
--js
--conf

# 设置显示
--noheading

# 定义新的文件类型
--type-set=conf=.conf

# 智能识别大小写
--smart-case
# 设置以less形式展示,设定less参数
--pager=less -R -M --shift 5 -i

ack 命令补充说明:


ack官网列出了这工具的5大卖点:

  1. 速度非常快,因为它只搜索有意义的东西。
  2. 更友好的搜索,忽略那些不是你源码的东西。
  3. 为源代码搜索而设计,用更少的击键完成任务。
  4. 非常轻便,移植性好。
  5. 免费且开源

ack 命令参数:


这些参数在linux上的适用频率是相当高的,尤其是你用vim做为IDE的话

-n, 显示行号
-l/L, 显示匹配/不匹配的文件名
-c, 统计次数
-v, invert match
-w, 词匹配
-i, 忽略大小写
-f, 只显示文件名,不进行搜索.
-h, 不显示名称
-v, 显示不匹配

ack 命令实例:


在记忆的时候大体上可以分为这几个部分:

  • Searching 代码搜索
  • Search output 搜索结果处理
  • File presentation 文件展示
  • File finding 文件查找
  • File inclusion/exclusion 文件过滤

grep 常用操作

grep -r 'hello_world' # 简单用法
grep '^hello_world' . # 简单正则
ls -l | grep .py # 管道用法

Searching


ack 简单的文本搜索,默认是递归的。默认情况下 ack-grep 会搜索当前目录下所有文件内容,只要包含关键字就会输出。

ack-grep hello
ack-grep -i hello
ack-grep -v hello
ack-grep -w hello
ack-grep -Q 'hello*'

Search File


ack 对搜索结果进行处理,比如只显示一个文件的一个匹配项,或者xxx

ack-grep --line=1       # 输出所有文件第二行
ack-grep -l 'hello'     # 包含的文件名
ack-grep -L 'print'     # 非包含文件名

File presentation


ack 输出的结果是以什么方式展示呢,这个部分有几个参数可以练习下

ack-grep hello --pager='less -R'    # 以less形式展示
ack-grep hello --noheading      # 不在头上显示文件
ack-grep hello --nocolor        # 不对匹配字符着色

File finding


没错,ack 它可以查找文件,以省去你要不断的结合 findgrep 的麻烦,虽然在 Linux 的思想是一个工具做好一件事。

ack-grep -f hello.py     # 查找全匹配文件
ack-grep -g hello.py$    # 查找正则匹配文件
ack-grep -g hello  --sort-files     # 查找然后排序

File Inclusion/Exclusion


ack 文件过滤,个人觉得这是一个很不错的功能。如果你曾经在搜索项目源码是不小心命中日志中的某个关键字的话,你会觉得这个有用。

ack-grep --python hello       # 查找所有python文件
ack-grep -G hello.py$ hello   # 查找匹配正则的文件

ack 扩展阅读:




ack 命令评论