Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using "awk print" to select last portion of a string

Status
Not open for further replies.

MHThomas

Technical User
Nov 25, 2002
26
GB
Hi,
Again I must apologise for my inadequacies as a scripter, I need a simple script to select the last section of a variable. I know how to use awk print basically, but can't find how to select the last portion. Please see my cut-down script below;



#!/usr/bin/ksh
file="/home/thomasm/test.txt"
first=`echo $file | awk -F"/" '{print $1}'`
last=`echo $file | awk -F"/" '{print $3}'`
echo $first $last
exit



This script picks up the first and last segments (in this case) but I expect variables of between 0 and 10 sections, I could code a cumbersome set of loops, but I'm sure there must be an easier way.

Cheers,

Mark T.
 
The output of:

#!/bin/ksh
file="/home/thomasm/test.txt"
first=`echo $file | awk -F"/" '{print $1}'`
last=`echo $file | awk -F"/" '{print $3}'`
echo "[${first}] [${last}]"

is:
[] [thomasm]

What you do you want you output really be?

[home] [test.txt]
[/home/thomasm] [test.txt]
[somethingElse] [somethingOther]

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 

why not just assign it to an array?

KSH

mystr=&quot;/this/is/a/big/string&quot;
set -A b `echo $mystr | sed -e 's#/# #g'`

echo &quot;b[0] == ${b[0]}&quot;
echo &quot;b[1] == ${b[1]}&quot;
echo &quot;b[2] == ${b[2]}&quot;
echo &quot;b[3] == ${b[3]}&quot;
echo &quot;b[4] == ${b[4]}&quot;


----



 
echo $file|awk -F&quot;/&quot;'{print $NF}'
NF is Number of Fields in which a line is tokenized
so this will print the last field, regarldess it's the 1st, the 2nd or the nth
 
You may also take a look at:
man basename
man dirname
Examples:
file=&quot;/home/thomasm/test.txt&quot;
echo &quot;dirname=`dirname $file`&quot;
echo &quot;filename=`basename $file`&quot;
As you're in ksh, you can do this:
echo &quot;dirname=${file%/*}&quot;
echo &quot;filename=${file##*/&quot;
In your ksh man page, pay attention to % and # in variable substitution.

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Thank you all, especially Sbix for the shortest, neatest solution.

Cheers,

Mark T.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top