Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with shell script.

Status
Not open for further replies.

galger

MIS
Jan 16, 2002
79
US
Need to change this script so it does not change date or permissions of file edited/copied.
and if possible- if file is being used by another process - do not touch and move on to next file.

Decription: change text within multiple files

:
# chtext - change text within multiple files

if [ $# -lt 3 ]
then
echo >&2 "usage: chtext old new [file ...]"
exit 1
fi

Old="$1"
New="$2"
shift; shift

for file
do
echo >&2 "chtext: change $file: $Old to $New"
if [ -r "$file" ]
then
if sed "s|$Old|$New|g" < "$file" > /tmp/ct$$
then
mv /tmp/ct$$ "$file"
else
echo >&2 "chtext: could not change file: $file"
fi
fi
done



 
Hi

If your [tt]sed[/tt] version support the -i option, then all is much simple. No need for [tt]if[/tt] and [tt]mv[/tt] and the file permissions will not change. ( Not a solution for keeping the file times too. )
Code:
for file
do
    echo >&2 "chtext: change $file: $Old to $New"
    [ -r "$file" ] && sed -i "s|$Old|$New|g" "$file"
    test $? -ne 0 && echo >&2 "chtext: could not change file: $file"
done
Otherwise just set the original permissions for the new file. See [tt]chmod[/tt], [tt]chown[/tt] and [tt]touch[/tt], they all have --reference= option.
To skip on files in use, just check them with [tt]lsof[/tt] or [tt]fuser[/tt], then step forward in the loop with [tt]continue[/tt], if necessary.
Code:
for file
do
    echo >&2 "chtext: change $file: $Old to $New"
    if fuser -s "$file"; then
      echo "$file in use by other process"
      continue
    end
    if [ -r "$file" ]
    then
    if sed "s|$Old|$New|g" < "$file" > /tmp/ct$$
    then
        chown --reference="$file" /tmp/ct$$
        chmod --reference="$file" /tmp/ct$$
        touch --reference="$file" /tmp/ct$$
        mv /tmp/ct$$ "$file"
    else
        echo >&2 "chtext: could not change file: $file"
    fi
    fi
done

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top