J.Doe
J.Doe

Reputation: 319

using awk command to get the correct name

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.

Upvotes: 0

Views: 140

Answers (1)

P....
P....

Reputation: 18391

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' 

Upvotes: 1

Related Questions