How to edit multiple text files with a single command?
You can use sed
:
sed -i.bak '1s/^.*$/new line/' *.txt
This will replace the first line of all .txt
files in the current directory with the text new line
, change it to meet your need.
Also the original files will be backed up with .bak
extension, if you don't want that just use :
sed -i '1s/^.*$/new line/' *.txt
Well, using vim
itself:
vim -Nesc 'bufdo call setline(1,"This is the replacement.") | wq' file1 file2 ...
What this does:
setline (n, text)
, well, is a function that sets linen
totext
.call
is needed to call functions.bufdo
is used to repeat a command across buffers (without a range, it acts on all buffers).wq
saves and quits the buffer. We need to do this before moving on to the next buffer, so this command is chained to thecall
command using|
.-c cmd
runscmd
is a command-mode command after loading the first buffer.Nes
turns on no-compatible, silent, ex-mode, which is better for non-interactive processing.
Benefits:
- The
setline
text content can be anything - an&
in ased
replacement text can have unintended effects.
A few other options:
awk
(needs a relatively new version of GNUawk
)$ awk -i inplace -vline="new line" '(FNR==1){print line; next}1;' *.txt
Perl/shell
$ for f in *txt; do perl -i -lne '$.==1 ? print "new line" : print' "$f" done
Shell/coreutils
$ for f in *txt; do ( echo "new line"; tail -n+2 "$f" ) > foo && mv foo "$f"; done