0

Log file name: "/home/msubra/WORK/tmo/LOG/BCH1043.9987.log"

From the above string i need to extract the content BCH1043.

The directory structure may differ so the solution should check for the string with BCH until the dot

Chaos
  • 11,213
  • 14
  • 42
  • 69
  • 2
    Erm. Ok. I'll ask first. What _exactly_ have you tried so far? What tools did you use? What exactly are you trying to do? Will the files always start with BCH and end with log? Remember, SO is there for getting help, not to have others do your work for you. – Markus W Mahlberg Nov 06 '14 at 16:24
  • you wan that dot too at last?? – Hackaholic Nov 06 '14 at 16:30

4 Answers4

1

No need to call basename, you can use parameter substitution that is built-in to the shell for the whole thing:

$ cat x.sh
filepath="/home/msubra/WORK/tmo/LOG/BCH1043.9987.log"

# Strip off the path.  Everything between and including the slashes.
filename=${filepath##/*/}

# Then strip off everything after and including the first dot.
part1=${filename%%.*}

echo $part1
$ ./x.sh
BCH1043
$

A dot in the filepath will not cause trouble either.

See section 4.5.4 here for more info: http://docstore.mik.ua/orelly/unix3/korn/ch04_05.htm

Oh and resist the temptation to get tricky and do it all in one line. Breaking into separate components is much easier to debug and maintain down the road, and who knows you may need to use those components too (the path and the rest of the file name).

Gary_W
  • 9,933
  • 1
  • 22
  • 40
0

try like this:

a="/home/msubra/WORK/tmo/LOG/BCH1043.9987.log"
echo ${a##*/} | cut -d "." -f 1

or
 basename $a | cut -d "." -f 1

or
 var=${a##*/}; echo ${var%%.*}

output:

BCH1043

It dosent include dot. Your question is not clear, but you can extract like that

${a##*/} will extract after last / like same as basename

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

basename will reduce /home/msubra/WORK/tmo/LOG/BCH1043.9987.log to BCH1043.9987.log

echo /home/msubra/WORK/tmo/LOG/BCH1043.9987.log | basename

You can use regular expressions, awk, perl, sed etc to extract "BCH1043" from "BCH1043.9987.log". First I need to know what the range of possible filenames is before I can suggest a regular expression for you.

Adam
  • 35,919
  • 9
  • 100
  • 137
0

Use basename to extract only the filename and then use parameter expansion to strip off the data you don't want.

log=/home/msubra/WORK/tmo/LOG/BCH1043.9987.log
log=$(basename "$log")
echo "${log%%.*}"

The following is almost equivalent but doesn't use the external basename process. However there are cases where it will give different results (though whether those cases are relevant here is up to you and your usage/input). See this answer for examples/details.

log=/home/msubra/WORK/tmo/LOG/BCH1043.9987.log
log=${log#*/}
echo "${log%%.*}"
Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148