linux - Bash 按关键字排序列表

标签 linux bash shell command-line scripting

我正在尝试编写一个 bash 脚本,该脚本采用输入流并将包含关键字的行排序到顶部。

起点:

$ cat file
cat
dog
mouse
bird
cat and mouse
lorem
ipsum

目标:

$ cat file | sort-by-keyword mouse
mouse
cat and mouse
cat
dog
bird
lorem
ipsum

我尝试使用排序来实现它,但失败了。是我不知道的另一种工具/方式吗?

最佳答案

使用sed:

脚本文件按关键字排序:

#!/bin/bash
input="$(cat)"
echo "$input" | sed "/$1/p;d"
echo "$input" | sed "/$1/!p;d"

用法:

chmod +x sort-by-keyword

cat file | ./sort-by-keyword mouse

关于linux - Bash 按关键字排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62213897/

相关文章:

linux - 用于计算文本文件中的 CR/LF 的 Bash 脚本

linux - 如何在gnuplot中将字符串转换为数字

linux - Linux 无效日期

linux - 内核线程和用户线程优先级

linux - 如果脚本从另一个脚本开始,Bash 陷阱将不起作用

bash - 保存 Crontab 文件

linux - 无法在 Linux 中更改权限为 0666 的文件的所有权

windows - VSCode 终端之前的命令

Bash 脚本,需要帮助⠀作业

bash - 在 bash/unix 中获取以前的日期