Modify a file without creating another file

Is there a way to modify a file without writing the contents to another file, without sed and awk?

For example:

$ cat test.txt
aaa
aaa
bbb
ccc
ddd

Replacing using sed with -i option, sed -i 's/aaa/NNN/g' test.txt will produce the following:

NNN
NNN
bbb
ccc
ddd

How to do that without awk and sed?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use a vi script:

$ vi test.txt -c '%s/aaa/NNN/ | wq'
$ cat test.txt
NNN
NNN
bbb
ccc
ddd

You’re simply automating what would normally be entered when using vi in command mode (accessed using Esc: usually):

% – carry out the following command on every line:

s/aaa/NNN/ – subtitute aaa with NNN

| – command delimiter

w – write changes to file

q – quit

Method 2

Using sponge:

#!/bin/bash

pattern='aaa'
replacement='NNN'

while read -r line
do                                                                              
  printf '%sn' "${line//$pattern/$replacement}"
done < "${1}"

Call with:

./script.sh test.txt | sponge test.txt

Method 3

With ed, the line editor:

ed -s test.txt <<< $',s/pattern/replace/gnwnq'

or

ed -s test.txt <<IN
,s/pattern/replace/g
w
q
IN

or

printf '%sn' ,s/pattern/replace/g w q | ed -s test.txt

Method 4

If you are using bash or ksh, you can use pattern substitution for shell variables. Note however, that basic shell globs are less powerful and extended shell globs have some features that sed doesn’t and vice versa. For more details, see ‘Parameter Expansion’ in man 1 bash:

t=$(< test.txt); printf '%sn' "${t//aaa/NNN}" >test.txt

Extended shell globs are disabled by default, so you may need to explicitly enable them:

shopt -s extglob

Method 5

You can also use perl

perl -pi -e 's/aaa/bbb/g' file.txt

This will give the output you desire.

You can also backup your original file automatically using i.bak instead of i. This will create a backup named file.txt.bak.

Method 6

You can use Vim in Ex mode:

ex -sc '%s/aaa/NNN/|x' test.txt
  1. % select all lines
  2. s substitute
  3. x save and close


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x