-2

I have these files which are my input:

library.WTHCG.30678-34569-2789.txt
library.WTHCG.45789-45688-7897.txt
library.WTHCG.56788-67879-7899.txt
library.WTHCG.45678-78987-9097.txt

and I'm running this command:

for i in library*; do
    echo sspace ${i#*library.} --o $i;
done

I'm using ${i#*library.} to remove library. from the beginning of the string. But I need to remove library. and .txt after --o at the same time, so that the results looks like:

sspace WTHCG.30678-34569-2789.txt --o WTHCG.30678-34569-2789
sspace WTHCG.45789-45688-7897.txt --o WTHCG.45789-45688-7897
sspace WTHCG.56788-67879-7899.txt --o WTHCG.56788-67879-7899
sspace WTHCG.45678-78987-9097.txt --o WTHCG.45678-78987-9097
tripleee
  • 158,107
  • 27
  • 234
  • 292
  • since you want to remove fixed length strings, one idea would be to use `bash` substrings, eg, `{var:start:length}`; skipping `library.` means we `start` at position `8`, `length` will be total length of `var` (`${#var}`) minus the length of our fixed length removals (`8` for `library.`, `4` for `.txt`): for `i='library.WTHCG.30678-34569-2789.txt'` we have `echo "${i:8:(${#i}-8-4)}"` => `WTHCG.30678-34569-2789`; **NOTE:** in this case the parens can be removed and still obtain the same result – markp-fuso Oct 10 '21 at 13:38
  • also added an answer to the linked (duplicate) question; assuming 3 variables ... `string`, `prefix` and `suffix` ... a general solution: `echo "${string:${#prefix}:${#string}-${#prefix}-${#suffix}}"` – markp-fuso Oct 10 '21 at 14:00

2 Answers2

1

You need two expansions to achieve this:

for filename in library*; do
    result=${filename#library.} # remove library. from beginning
    result=${result%.txt}       # remove .txt from the end
    echo sspace "${result}" --o "${filename}"
done
hek2mgl
  • 143,113
  • 25
  • 227
  • 253
0

There is no way to perform multiple parameter expansions in one go; you need to use a temporary variable.

for i in library*; do
    j=${i#*library_}
    echo sspace "$j" --o "${j%.txt}"
done
tripleee
  • 158,107
  • 27
  • 234
  • 292