How do i append some text to pipe without temporary file

廉价感情. 提交于 2019-12-25 06:57:32

问题


I am trying to get the max version number from a directory where i have several versions of one program

for example if output of ls is

something01_1.sh
something02_0.1.2.sh
something02_0.1.sh
something02_1.1.sh
something02_1.2.sh
something02_2.0.sh
something02_2.1.sh
something02_2.3.sh
something02_3.1.2.sh
something.sh

I am getting the max version number with the following -

ls somedir | grep some_prefix | cut -d '_' -f2 | sort -t '.' -k1 -r | head -n 1

Now if at the same time i want to check it with the version number which i already have in the system, whats the best way to do it...

in bash i got this working (if 2.5 is the current version)

(ls somedir | grep some_prefix | cut -d '_' -f2; echo 2.5) | sort -t '.' -k1 -r | head -n 1

is there any other correct way to do it?

EDIT: In the above example some_prefix is something02.

EDIT: Actual Problem here is

(ls smthing; echo more) | sort 

is it the best way to merge output of two commands/program for piping into third.


回答1:


I have found the solution. The best way it seems is using process substitution.

cat <(ls smthing) <(echo more) | sort

for my version example

cat <(ls somedir | grep some_prefix | cut -d '_' -f2) <(echo 2.5) | sort -t '.' -k1 -r | head -n 1

for the benefit of future readers, I recommend - please drop the lure of one-liner and use glob as chepner suggested.

Almost similar question is asked on superuser.

more info about process substitution.




回答2:


Is the following code more suitable to what you're looking for:

#/bin/bash

highest_version=$(ls something* | sort -V | tail -1 | sed "s/something02_\|\.sh//g")
current_version=$(echo $0 | sed "s/something02_\|\.sh//g")

if [ $current_version > $highest_version ]; then
    echo "Uh oh! Looks like we need to update!";
fi



回答3:


You can try something like this :

#! /bin/bash

lastversion() { # prefix
  local prefix="$1" a=0 b=0 c=0 r f vmax=0

  for f in "$prefix"* ; do
    test -f "$f" || continue
    read a b c r <<< $(echo "${f#$prefix} 0 0 0" | tr -C '[0-9]' ' ')
    v=$(((a*100+b)*100+c))
    if ((v>vmax)); then vmax=$v; fi
  done
  echo $vmax  
}

lastversion "something02"

It will print: 30102



来源:https://stackoverflow.com/questions/15441744/how-do-i-append-some-text-to-pipe-without-temporary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!