3

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?

spekulatius
  • 1,434
  • 14
  • 24

3 Answers3

1

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
$

Digvijay S
  • 2,665
  • 1
  • 9
  • 21
1

One dirty way to achieve it:

grep mouse file && grep -v mouse file
mtnezm
  • 1,009
  • 1
  • 7
  • 19
1

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
MichalH
  • 1,062
  • 9
  • 20