ms. sakura
ms. sakura

Reputation: 201

How can I edit the content of a file in shell script?

Are there other alternatives aside from sed? I meant a command that does this in shell script

cat file1 and it contains the following:

How
are
you

But suppose I want to change the word "How" into "Who"?

Upvotes: 0

Views: 133

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

There are a variety of alternatives to sed, but sed is probably the tool of choice for this particular operation. The alternatives include:

  • ed
  • ex
  • Perl
  • Python
  • Ruby
  • awk

The ed and ex commands are similar:

ed ff <<!
g/How/s//Who/g
w
q
!

You can write ex instead of ed.

perl -i.bak -p -e 's/\bHow\b/Who/g' ff

awk '{ gsub(/How/, "Who"); print }' ff

I'm not fluent enough in Python or Ruby to give idiomatic solutions.

But sed, especially GNU sed with the -i option, is pretty convenient too:

sed -i 's/How/Who/g' ff

Without the -i option (and the -i option is not completely idiot-proof, if you've got an idiot like me with symlinks or multiple links to a single file in play), you can use:

sed 's/How/Who/g' ff > ff.$$
cp ff.$$ ff
rm -f ff.$$

Or, with traps to ensure no residual temporary files:

tmp=ff.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
sed 's/How/Who/g' ff > ff.$$
cp ff.$$ ff
rm -f ff.$$
trap 0

Upvotes: 1

Related Questions