user2864207
user2864207

Reputation: 343

How to extract a string at end of line after a specific word

I have different location, but they all have a pattern:

some_text/some_text/some_text/log/some_text.text

All locations don't start with the same thing, and they don't have the same number of subdirectories, but I am interested in what comes after log/ only. I would like to extract the .text

edited question:

I have a lot of location:

/s/h/r/t/log/b.p
/t/j/u/f/e/log/k.h
/f/j/a/w/g/h/log/m.l

Just to show you that I don't know what they are, the user enters these location, so I have no idea what the user enters. The only I know is that it always contains log/ followed by the name of the file.

I would like to extract the type of the file, whatever string comes after the dot

Upvotes: 0

Views: 3716

Answers (5)

nortally
nortally

Reputation: 347

Running from the root of this structure:

    /s/h/r/t/log/b.p
    /t/j/u/f/e/log/k.h
    /f/j/a/w/g/h/log/m.l

This seems to work, you can skip the echo command if you really just want the file types with no record of where they came from.

    $ for DIR in *; do
    >  echo -n "$DIR  "
    >  find $DIR -path "*/log/*" -exec basename {} \; | sed 's/.*\.//'
    > done
    f  l
    s  p
    t  h

Upvotes: 0

jkshah
jkshah

Reputation: 11703

Using awk

awk -F'.' '{print $NF}' file

Using sed

sed 's/.*\.//' file

Upvotes: 0

dogbane
dogbane

Reputation: 274612

You can use bash built-in string operations. The example below will extract everything after the last dot from the input string.

$ var="some_text/some_text/some_text/log/some_text.text"
$ echo "${var##*.}"
text

Alternatively, use sed:

$ sed 's/.*\.//' <<< "$var"
text

Upvotes: 1

Kent
Kent

Reputation: 195059

THe only i know is that it always contains log/ followed by the name of the file.

I would like to extract the type of the file, whatever string comes after the dot

based on this requirement, this line works:

grep -o '[^.]*$' file

for your example, it outputs:

text

Upvotes: 1

James Gawron
James Gawron

Reputation: 969

Not the cleanest way, but this will work

sed -e "s/.*log\///" | sed -e "s/\..*//"

This is the sed patterns for it anyway, not sure if you have that string in a variable, or if you're reading from a file etc.

You could also grab that text and store in a sed register for later substitution etc. All depends on exactly what you are trying to do.

Upvotes: 0

Related Questions