I need a linux bash script to loop a folder for all files and check if there is a string in them, change another string of them. For example we check if file contanis AAAA then replace BBBB with CCCC and if didn't have AAAA we change DDDD to EEEE.

I wrote some codes but I'm not sure if they work correctly:

#!/bin/bash

PATH = /path/to/files/* # files has no extension

for file in $PATH; do
    if grep -q "AAAA" $file; then
        replace "BBBB" "CCCC" -- $file
    else
        replace "DDDD" "EEEE" -- $file
    fi
done
share|improve this question
2  
What have you tried ? – X.L.Ant Dec 17 '12 at 13:03
Please paste that code here, we will help you to resolve the issues. – mandy Dec 17 '12 at 13:09
1  
I've just edited the post. Thanks – PRO MAX Dec 17 '12 at 13:10

2 Answers

up vote 0 down vote accepted

A one-liner doing your job :

for i in /path/to/files/* ; do if grep -q AAAA "$i" ; then sed -i 's/BBBB/CCCC/g' "$i" ; else sed -i 's/DDDD/EEEE/g' "$i" ; fi ; done   
share|improve this answer
Thanks. Can I write everything instead AAAA ?! I need to write something like this: AA=AA , Does the equal break the code ?! – PRO MAX Dec 17 '12 at 13:21
Yes you can ;). grep accept regular expression as pattern by default. – Pierre-Louis Laffont Dec 17 '12 at 13:25
1  
grep and sed will grumble about directories and calling it a one-liner is pushing it. – sudo_O Dec 17 '12 at 13:50
"Does the equal break the code?" : No, but a / can ;)... for that replace slashes in 's/BBBB/CCCC/g' with some other character like | or #, which is not present in the search nor replace string. :-) – anishsane Dec 17 '12 at 14:52

A couple of things: PATH is not a good variable name, see here for information about the PATH variable, i'm not familiar with the replace command or how widely available it is but sed is probably a better choice for portability, sed -i 's/AAAA/BBBB/g' replaces all values of AAAA with BBBB in a file, also you should always quote your variables:

#!/bin/bash

for file in /path/to/file/*; do       
    if grep -q "AAAA" "$file"; then
        sed -i 's/BBBB/CCCC/g' "$file"
    else
        sed -i 's/DDDD/EEEE/g' "$file"
    fi
done

$ cat f1.txt 
AAAA
BBBB
DDDD

$ cat f2.txt
BBBB
DDDD

$ ./script.sh 

$ cat f1.txt
AAAA
CCCC
DDDD

$ cat f2.txt
BBBB
EEEE

This will have an issue with directories so an improvement using find to select only files and also now handles files with spaces:

#!/bin/bash

find /path/to/file/ -maxdepth 1 -type f -name | while IFS= read -r file
do
    if grep -q "AAAA" "$file"; then
        sed -i 's/BBBB/CCCC/g' "$file"
    else
        sed -i 's/DDDD/EEEE/g' "$file"
    fi
done
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.