简体   繁体   English

Bash 按关键字排序列表

[英]Bash sorting list by keyword

I'm trying to write a bash script that takes an input stream and sorts lines containing a keyword to the top.我正在尝试编写一个 bash 脚本,该脚本接受输入 stream 并将包含关键字的行排序到顶部。

Starting point:初始点:

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

Goal:目标:

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

I've tried to implement this using sort but failed.我尝试使用 sort 来实现这一点,但失败了。 Is another tool/way I'm not aware of?是我不知道的另一种工具/方式吗?

You can not sorting rest of the records.您不能对记录的 rest 进行排序。 Based on input.基于输入。 please try请试试

awk '{if ($0 ~ /mouse/) {print} else {a[NR]=$0}} END {for (i in a) print a[i]}'

Demo:演示:

$cat file.txt 
cat
dog
mouse
bird
cat and mouse
lorem
ipsum
$awk '{if ($0 ~ /mouse/) {print} else {a[NR]=$0}} END {for (i in a) print a[i]}' file.txt 
mouse
cat and mouse
bird
lorem
ipsum
cat
dog
$

One dirty way to achieve it:实现它的一种肮脏方法:

grep mouse file && grep -v mouse file

Using sed :使用sed

script file sort-by-keyword :脚本文件sort-by-keyword

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

Usage:用法:

chmod +x sort-by-keyword

cat file | ./sort-by-keyword mouse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM