0

I have a directory of files with the following naming scheme:

<project name>-<group name>.txt

I want to extract <group name> from the files I am looping through:

#!/bin/sh

for f in *; do
    echo "group name: ${f}"
done

How can this be done? I am experimenting with ${f##...} and ${f%...} but without success so far. I am unsure if they can be combined, so I can first leave out the prefix <project name>- and then leave out the suffix .txt.

Bradson
  • 615
  • 1
  • 6
  • 9

2 Answers2

0

I don't know if it's possible in one line, but if you go in steps it's easy:

for f in *.txt; do
    base=${f%.txt}
    projectname=${base%-*}
    groupname=${base#*-}
    echo project name: $projectname
    echo group name: $groupname
done

If you're OK with calling an external program, this also works and is pretty readable.

for f in *.txt; do
    groupname=$(basename ${f#*-} .txt)
    echo group name: $groupname
done
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0
for file in *-*.txt; do
    # shortest match: a-b-c-d.txt => d
    [[ $file =~ ([^-]+).txt$ ]] && echo "${BASH_REMATCH[1]}"
    # longest match: a-b-c-d.txt => b-c-d
    [[ $file =~ -(.+).txt$ ]] && echo "${BASH_REMATCH[1]}"
done
PesaThe
  • 7,259
  • 1
  • 19
  • 43
  • 1
    change to `/bin/bash` – PesaThe Jul 06 '18 at 14:42
  • I did not know about `BASH_REMATCH`, but this is what I needed. Thanks for your answer. – Bradson Jul 06 '18 at 14:52
  • @PesaThe The `bash` executable isn’t always in `/bin`. It’s usually more portable to use something like `#!/usr/bin/env bash`. (It’s also more portable to not use Bashisms, but since avoiding then is harder than typing 8 extra characters per script, they’re often worth the cost). – Daniel H Jul 06 '18 at 15:16