1835670 Members
2909 Online
110082 Solutions
New Discussion

Update content

 
SOLVED
Go to solution
peterchu
Super Advisor

Update content

IF I have a file , the file content is as below , there are so many word "abc" , I want to change all these word to another word "def" , except change it manually , what can I do ? thx.

# vi abc.txt
..abc....
.abc.....
...abc..
....abc.
"
"
10 REPLIES 10
Slawomir Gora
Honored Contributor
Solution

Re: Update content

Hi,

sed -e 's/abc/def/g' abc.txt > abc_new.txt
peterchu
Super Advisor

Re: Update content

thx Gola's reply,

I have one more requirement , if I want to update all files under a directory ( not only abc.txt , eg , all file under /home ) , what can I do ? thx.
Slawomir Gora
Honored Contributor

Re: Update content

Hi

ex.

cd /home
for f in `ls`
do
mv $f $f.tmp
sed -e 's/def/def/g' $f.tmp > $f
rm $f.tmp
done
Sanjay Kumar Suri
Honored Contributor

Re: Update content

You can do this through vi as well:

vi file
Press Esc

:1,$ s/abc/def/g
:wq!

sks
A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.
Slawomir Gora
Honored Contributor

Re: Update content

Hi,

more correct version :)


cd put_dir

for f in `ls`
do
if [ -d $f ]
then
echo "$f -> directory"
else
mv $f $f.tmp
sed -e 's/def/def/g' $f.tmp > $f
rm $f.tmp
fi
done

peterchu
Super Advisor

Re: Update content

thx Gora again,

your method seems too complicate for me , can I use "find" to do it ? thx.
Brian Markus
Valued Contributor

Re: Update content

I put this together for you. I hope it helps.


#!/bin/sh
count=1
for files in `ls -1 *.txt`
do
count=`expr $count + 1`
echo $count
sed -e 's/abc/def/g' $files > abc_new${count}.txt
done


-Brian.
When a sys-admin say's maybe, they don't mean 'yes'!
Ermin Borovac
Honored Contributor

Re: Update content

Yet another way with perl

perl -pi.orig -e 's,abc,def,g' *.txt

Original files will be saved with .orig suffix.

peterchu
Super Advisor

Re: Update content

thx all replies,

As my above post , if I want to update all files under a directory ( , eg , all files under the directory /home , not only abc.txt ) , what can I do ? thx
Sanjay Kumar Suri
Honored Contributor

Re: Update content

Use can use Brian script with following change.

cd /home
mkdir /home/temp

#!/bin/sh
count=1
for files in `ls`
do
count=`expr $count + 1`
echo $count
sed -e 's/abc/def/g' $files > temp/$files
done


Then move the file from temp back to /home.

sks
A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.