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?

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, does exactly what I hoped for
Hey MichalH, do you know a way to loop over a list of keyword from a file and run the command for each of them too? That would solve the next step for me
You can do that in a for loop, have a look at this answer stackoverflow.com/a/1521498/4270339.
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
$

Comments

1

One dirty way to achieve it:

grep mouse file && grep -v mouse file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.