Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve the order of the output of the command when piping to fzf

Tags:

bash

fzf

I have bash function that allows me to copy a line from history. Here's the function

history_cp() {
  history | 
    sort --reverse --numeric-sort | 
    fzf | 
    awk '{ $1=""; print }' | 
    tr -s ' ' | 
    xclip -selection clipboard 
}

It works fine, but fzf doesn't maintain the order of the results, how do i keep the sorted results?

like image 425
The.Wolfgang.Grimmer Avatar asked Nov 28 '25 17:11

The.Wolfgang.Grimmer


1 Answers

So, as mentioned in the comments --no-sort will prevent fzf from doing its own sorting.

I made a few adjustments to the function, trim it for whitespace front and back, and trim new lines as well (it seems that the existing tr -s '' doesn't work on older/all Linux distros).

Finally, since xclip will throw an error when no input is passed to it (like in the case where you run the function and then type ctrl-x) I've added this 2>/dev/null to suppress the errors.

history_cp() {
  history | 
    sort --reverse --numeric-sort | 
    fzf --no-sort | 
    awk '{ $1=""; print }' | 
    xargs | 
    tr -d '\n' | 
    xclip -selection clipboard 2>/dev/null
}

And since I'm using Mac and I liked what you were doing, here is an adaptation that works on MacOS.

history_cp() {
  history | 
    sort --reverse --numeric-sort | 
    fzf --no-sort | 
    awk '{ $1=""; print }' | 
    xargs | 
    tr -d '\n' | 
    pbcopy
}
like image 75
stzov Avatar answered Dec 01 '25 08:12

stzov