1

I have a WordPress site and want to change first line of all php files recursively using bash. How should I do? I am not very familiar with bash.

Thanks!

pictoru
  • 722
  • 6
  • 17
  • What have you tried? Loop through files (http://stackoverflow.com/questions/14823830/bash-for-loop-over-specific-files-in-a-directory) and make your change...? – naththedeveloper Feb 20 '14 at 10:12

3 Answers3

5

Change first line to some other line:

sed -i '1s/.*/changed line/' *.php

Adding a line before first line:

sed -i '1s/^/changed line\n/' *.php
anishsane
  • 20,270
  • 5
  • 40
  • 73
  • While it worked, it also modified all the line endings in my files. In vim I see ^M at the end. – hakunin Jan 21 '20 at 05:23
3

In order to modify the first line of the file, you can use this :

awk 'NR==1 {$0="what you want"} 1' *.php

You'll find more info here : bash: replace an entire line in a text file

Then to do it recursively, you can use a find first and then execute the awk command on every found file.

find . -name "*.php" -exec awk 'NR==1 {$0="what you want"} 1'

More info about the find command here : https://www.gnu.org/software/findutils/manual/html_mono/find.html#Scope

Community
  • 1
  • 1
Theox
  • 1,363
  • 9
  • 20
2

I used both above answers and executed the following:

find . -name "*.php" -exec sed -i '1 s/.*/<?php/' '{}' \;

So thanks both of you Theox and anishsane for your help

pictoru
  • 722
  • 6
  • 17