Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a bash script called test.sh that uses command-line argument:

lynx -dump $1 > $name".txt"

But I need name to be created from the argument by specific keywords in the argument.

An example is:


Both are two separate articles but are the difference can only be seen in those 12 characters. How do I create a variable from a url for those 12 characters? So that when I run test.sh in Terminal:

./test.sh http://www.pcmag.com/article2/0,2817,2412941,00.asp 

there is a text file saved as 0,2817,2412941,00?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can do it in awk like this:

$ name=$(echo $1 | awk -F[/.] '{print $(NF-1)}')
$ echo $name

By using / and . as delimiters, the stuff you want will be present in the last but one field which can be accessed using NF-1

share|improve this answer
This worked! Thank you! –  user1883614 Dec 7 '12 at 22:41

You can use the basename command:

basename http://www.pcmag.com/article2/0,2817,2412919,00.asp ".asp"

which will give you:

share|improve this answer
This works for one link but I'm dealing with over 100 links and the job would become tedious. But thank you nevertheless! –  user1883614 Dec 7 '12 at 22:42
You could of course also use another line to get the extension first, and then use it in this line. But then you're indeed better of with Gurus solution. –  Gerhard Burger Dec 8 '12 at 9:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.