Display
Display

Reputation: 23

bash filename start matching

I've got a simple enough question, but no guidance yet through the forums or bash. The question is as follows:

I want to add a prefix string to each filename in a directory that matches *.h or *.cpp. HOWEVER, if the prefix has already been applied to the filename, do NOT apply it again.

Why the following doesn't work is something that has yet to be figured out:

for i in *.{h,cpp}
do
if [[ $i!="$pattern*" ]]
then mv $i $pattern$i
fi
done

Upvotes: 2

Views: 7543

Answers (4)

Gordon Davisson
Gordon Davisson

Reputation: 125998

Others have shown replacements comparisons that work; I'll take a stab at why the original version didn't. There are two problems with the original prefix test: you need spaces between the comparison operator (!=) and its operands, and the asterisk was in quotes (meaning it gets matched literally, rather than as a wildcard). Fix these, and (at least in my tests) it works as expected:

if [[ $i != "$pattern"* ]]

Upvotes: 2

DigitalRoss
DigitalRoss

Reputation: 146151

#!/bin/sh
pattern=testpattern_
for i in *.h *.cpp; do
  case "$i" in
     $pattern*)
        continue;;
      *)
        mv "$i" "$pattern$i";;
  esac
done

This script will run in any Posix shell, not just bash. (I wasn't sure if your question was "why isn't this working" or "how do I make this work" so I guessed it was the second.)

Upvotes: 1

codaddict
codaddict

Reputation: 455322

you can try this:

for i in *.{h,cpp}
do
if ! ( echo $i | grep -q "^$pattern" ) 
# if the file does not begin with $pattern rename it.
then mv $i $pattern$i
fi
done

Upvotes: 2

falstro
falstro

Reputation: 35677

for i in *.{h,cpp}; do
  [ ${i#prefix} = $i ] && mv $i prefix$i
done

Not exactly conforming to your script, but it should work. The check returns true if there is no prefix (i.e. if $i, with the prefix "prefix" removed, equals $i).

Upvotes: 0

Related Questions