user3412751
user3412751

Reputation: 17

How to use grep in a for loop

Could someone please help with this script. I need to use grep to loop to through the filenames that need to be changed.

#!/bin/bash

file=

for file in  $(ls $1)

do

grep "^.old" |  mv  "$1/$file"  "$1/$file.old"

done

Upvotes: 0

Views: 2109

Answers (2)

Hai Vu
Hai Vu

Reputation: 40733

If I understand your question correctly, you want to make rename a file (i.e. dir/file.txt ==> dir/file.old) only if the file has not been renamed before. The solution is as follow.

#!/bin/bash

for file in "$1/"*
do
    backup_file="${file%.*}.old"
    if [ ! -e "$backup_file" ]
    then
        echo mv "$file" "$backup_file"
    fi
done

Discussion

The script currently does not actual make back up, it only displays the action. Run the script once and examine the output. If this is what you want, then remove the echo from the script and run it again.

Update

Here is the no if solution:

ls "$1/"* | grep -v ".old" | while read file
do
    echo mv "$file" "${file}.old"
done

Discussion

  • The ls command displays all files.
  • The grep command filter out those files that has the .old extension so they won't be displayed.
  • The while loop reads the file names that do not have the .old extension, one by one and rename them.

Upvotes: 0

chepner
chepner

Reputation: 531345

bash can handle regular expressions without using grep.

for f in "$1"/*; do
    [[ $f =~ \.old ]] && continue
    # Or a pattern instead
    # [[ $f == *.old* ]] && continue
    mv "$f" "$f.old"
done

You can also move the name checking into the pattern itself:

shopt -s extglob
for f in "$1/"!(*.old*); do
    mv "$f" "$f.old"
done

Upvotes: 2

Related Questions