How do i append some text to pipe without temporar

2019-08-31 02:19发布

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.

3条回答
不美不萌又怎样
2楼-- · 2019-08-31 02:35

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

查看更多
叛逆
3楼-- · 2019-08-31 02:36

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
查看更多
smile是对你的礼貌
4楼-- · 2019-08-31 02:40

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.

查看更多
登录 后发表回答