Kelly Beard
Kelly Beard

Reputation: 702

Trimming pathnames beyond a keyword (awk, sed, ?)

I want to trim a pathname beyond a certain point after finding a keyword. I'm drawing a blank this morning.

/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java

I want to find the keyword Java, save the pathname beyond that (tsupdater), then cut everything off after the Java portion.

Upvotes: 1

Views: 132

Answers (4)

Sicco
Sicco

Reputation: 6271

I'm not entirely sure what you want as output (please specify more clearly), but this command:

echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java" | sed 's/.*Java//'

results in:

/tsupdater/src/tsupdater.java

If you want the preceding part then this command:

echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java" | sed 's/Java.*//'

results in:

/home/quikq/1.0/dev/

Upvotes: 1

Kelly Beard
Kelly Beard

Reputation: 702

Like I said, I was having a weird morning, but it dawned on me.

echo /home/quikq/1.0/dev/Java/TSUpdater/src/TSUpdater.java | sed s/Java.*//g

Yields

/home/quikq/1.0/dev

Lots of great tips here for chopping it up different ways though. Thanks a bunch!

Upvotes: 0

I don't know if this is what you want, but you can split the pathname into two with:

echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java" | sed 'h;s/.*Java//p;g;s/Java.*/Java/'

Which outputs:

/tsupdater/src/tsupdater.java
/home/quikq/1.0/dev/Java

If you would like to save the second part into a file part2.txt and print the first part, you could do:

echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java" | sed 'h;s/.*Java//;wpart2.txt;g;s/Java.*/Java/'

If you're writing a shell script:

myvar="/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java"
part1="${myvar%Java*}Java"
part2="${myvar#*Java/}"

Hope this helps =)

Upvotes: 3

Kent
Kent

Reputation: 195059

take one you need:

kent$  echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java"|sed -r 's#(.*Java/[^/]*).*#\1#g'
/home/quikq/1.0/dev/Java/tsupdater

kent$  echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java"|sed -r 's#(.*Java).*#\1#g' 
/home/quikq/1.0/dev/Java

kent$  echo "/home/quikq/1.0/dev/Java/tsupdater/src/tsupdater.java"|sed -r 's#.*Java/([^/]*).*#\1#g' 
tsupdater

Upvotes: 1

Related Questions