Heero Yuy
Heero Yuy

Reputation: 614

How to replace the first line of every files found using "find"

I have the list of files to replace the first line from running this command

find . -type f -name ".txt"

I want to replace the first line of the files found with this text "line 1"

Doing my research I found a way to delete the first line with

ex -sc '1d|x' file.txt

then prepend a file with

echo "line 1"|cat - file.txt > out && mv out file.txt

but I don't know how to delete first line and prepend for every files found

Upvotes: 2

Views: 211

Answers (2)

mroach
mroach

Reputation: 2478

You can use exec or xargs with find, but for more complicated commands I always run processing in a loop. It's clearer that way. Here's what you can do:

find . -type f -name '*.txt' | while read -r f; do
  ex -sc '1d|x' "$f"
  echo "line 1"|cat - "$f" > out && mv out "$f"
done

Upvotes: 0

Diego Torres Milano
Diego Torres Milano

Reputation: 69388

You can use exec

find . -name "*.txt" -exec sed -i .ORI '1s/.*/line 1/' {} \;

to edit the files in place saving backups as .ORI.

Upvotes: 4

Related Questions