Bash sorting list by keyword

Viewed 834

I'm trying to write a bash script that takes an input stream and sorts lines containing a keyword to the top.

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. Is another tool/way I'm not aware of?

3 Answers

You can not sorting rest of the records. 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:

script file 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
Related