Visit Jeremy's Blog.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 06-30-2004, 04:37 AM   #1
Registered: Oct 2002
Location: Ayrshire, Scotland
Distribution: Suse(home) RHEL (Work)
Posts: 263

Rep: Reputation: 30
awk - simple 'for' loop doing my nut...

I want to create an awk script that, passed a URL, trims off the final section (everything after the last '/'

I've created the following in a file trim.awk:


BEGIN { FS="/"
new_var = "" }

{ for (count_var=1; count_var<NF; count_var++) {
new_var = $new_var$count_var
print count_var " - " $count_var " - " $new_var }


I'm calling it from the command line with:

echo "" | awk -f trim.awk

The results I get are far from what I expected:

1 - -
2 - this -
3 - is -
4 - a -

In other words, my $new_var is returning the whole input string every time, regardless of what it's assigned to...

Any ideas? I presume I'm doing something basic wrong, but I've been looking at this for a whole day...

Old 06-30-2004, 07:17 AM   #2
Registered: Oct 2002
Location: Ayrshire, Scotland
Distribution: Suse(home) RHEL (Work)
Posts: 263

Original Poster
Rep: Reputation: 30
After a flash of inspiration and some more googling, I came up with the following solution. The problem was with using $ with variable names...


BEGIN { FS="/" }

{ for (count_var=1; count_var<NF; count_var++) {
new_var = new_var$count_var"/"
print new_var

Old 06-30-2004, 08:54 AM   #3
Registered: Jun 2004
Location: Surrey, UK
Distribution: Mandrake 10 Download
Posts: 73

Rep: Reputation: 16
I know the following command was never designed for this but did you consider using:


However, if you are doing what you are doing as an excercise in awk then fair enough


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Simple question about sed or awk setianusa Programming 2 09-16-2005 03:57 PM
Simple bash/awk/sed scripting question R00ts Programming 4 04-16-2005 02:55 AM
[c shell] simple for loop saiz66 Programming 1 09-28-2004 07:02 PM
Simple for loop lappen Programming 10 09-26-2004 06:36 AM
How to loop or sort in bash, awk or sed? j4r0d Programming 1 09-09-2004 03:22 AM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:38 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration