tags:

views:

48

answers:

4

Given paths like this:

/data/mirrors/third-party/centos/5/projectA/x86_64
/data/mirrors/third-party/centos/5/projectA/i386
/data/mirrors/third-party/centos/5/projectA/noarch
/data/mirrors/third-party/centos/4/projectB/x86_64
/data/mirrors/third-party/centos/4/projectB/i386
/data/mirrors/third-party/centos/4/projectB/noarch
/data/mirrors/third-party/centos/4/projectC/x86_64
/data/mirrors/third-party/centos/4/projectC/i386
/data/mirrors/third-party/centos/4/projectC/noarch

How can I grab the values from field 5 and 7 ('5' and 'x86_64') using Bash shell commands?

I have something like this so far, but I'm looking for something more elegant, and without the need to capture the 'junk*':

cd /data/mirrors/third-party/centos/5/project/x86_64
echo `pwd` | tr '/' ' ' | while read junk1 junk2 junk3 junk4 version junk5 arch; do
    echo version=$version arch=$arch
done
version=5 arch=x86_64
A: 

try this

echo `pwd` | cut -d'/' -f6,8 | tr '/' ' '

to display field

or to display with sring version and arch

echo `pwd` | cut -d'/' -f6,8 | sed -e 's/\(.*\)\/\(.*\)/version=\1 arch=\2/'
jcubic
I think you want fields 6 and 8 in this case. The blank before the root / is considered a field.
Karl Bielefeldt
+1  A: 

This works for me:

pwd | awk -F'/' '{print "version=" $6 " arch=" $8}'
gpojd
+1  A: 
> p=$(pwd)
> echo $p
/data/mirrors/third-party/centos/5/projectA/x86_64

> basename ${p}
x86_64

> basename ${p%/*/*}
5

You can also use something like:

echo `expr match "$p" '<regular-expression>'`

...perhaps someone might help me with that regular expression ;)

merv
+1  A: 

You can use IFS and an array to split the directory into its components:

#!/bin/bash
saveIFS=$IFS
IFS='/'
dirs=($(pwd))
IFS=$saveIFS
version=${dirs[5]}
arch=${dirs[7]}
Dennis Williamson