0

I want to get the filename from a long string in shell script.After reading some example from likegeeks.com,I write a simple solution:

#/bin/bash

cdnurl="http://download.example.com.cn/download/product/vpn/rules/vpn_patch_20190218162130_sign.pkg?wsSecret=9cadeddedfr7bb85a20a064510cd3f353&wsABSTime=5c6ea1e7"
echo ${cndurl}

url=`echo ${cdnurl} | awk -F'/' '{ print $NF }'`
result=`echo ${url} | awk -F '?' '{ print $1}'`
echo ${url}

echo ${result}

I just want to get vpn_patch_20190218162130_sign.pkg,and the it does.I wonder is there any smart ways (may be one line).

If behind pkg it's not ?,how to use pkg to get the filename,I am not sure if always ? after pkg,but the filename always be *.pkg.

J.Doe
  • 319
  • 1
  • 8

1 Answers1

1

You can try : this is more robust as compare to second awk command:

echo "$cdnurl"|awk -v FS='/' '{gsub(/?.*/,"",$NF);print $NF}'
vpn_patch_20190218162130_sign.pkg

#less robust
echo "$cdnurl"|awk -vFS=[?/] '{print $(NF-1)}'

You should use sed :

sed -r 's|.*/(.*.pkg).*|\1|g' 
P....
  • 17,421
  • 2
  • 32
  • 52
  • If behind pkg it's not ?,how to use pkg to get the filename,I am not sure if always ? after pkg. – J.Doe Feb 21 '19 at 17:32
  • @J.Doe can you add example URL where there in no `?` ? – P.... Feb 21 '19 at 18:46
  • `-v FS` == `-F` – karakfa Feb 21 '19 at 20:50
  • @PS. http://download.example.com.cn/download/product/vpn/rules/vpn_patch_20190218162130_sign.pkgdwsSecret=9cadeddedfr7bb85a20a064510cd3f353&wsABSTime=5c6ea1e7,maybe use _sign.pkg to get the name ,but the wsSecrt may get the same value,it struck me. – J.Doe Feb 22 '19 at 03:03
  • @J.Doe you should try `sed -r 's|.*/(.*.pkg).*|\1|g'` – P.... Feb 22 '19 at 03:40
  • @PS. thanks for your answer,I use echo "$cdnurl"|awk -v FS='/' '{gsub(/?.*/,"",$NF);print $NF}',someday it gives a error msg:awk: line 1: regular expression compile failed (missing operand) ?.* – J.Doe Mar 07 '19 at 07:33
  • @PS. sed -r 's|.*/(.*.pkg).*|\1|g' this now works well. – J.Doe Mar 07 '19 at 07:34