-3

I have a lot of files, where I would like to edit only those lines that start with private.

It principle I want to

gawk '/private/{gsub(/\//, "_"); gsub(/-/, "_"); print}' filename

but this only prints out the modified part of the file, and not everything.

Question

  • Does gawk have a way similar to sed -i inplace?
  • Or is there are much simpler way to do the above woth either sed or gawk?
oguz ismail
  • 1
  • 16
  • 47
  • 69
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162

2 Answers2

1

GNU awk from 4.1.0 has the in place ability.
And you should put the print outside the reg match block.
Try this:

gawk '/^private/{gsub(/[/-]/, "_");} 1' filename

or, make sure you backed up the file:

gawk -i inplace '/^private/{gsub(/[/-]/, "_");} 1' filename

You forgot the ^ to denote start, you need it to change lines started with private, otherwise all lines contain private will be modified.
And yeah, you can combine the two gsubs with a single one.

The sed command to do the same would be:

sed '/^private/{s/[/-]/_/g;}' filename

Add the -i option when you done testing it.

Til
  • 5,150
  • 13
  • 26
  • 34
1

Just move the final print outside of the filtered pattern. eg:

gawk '/private/{gsub(/\//, "_"); gsub(/-/, "_")} {print}' 

usually, that is simplified to:

gawk '/private/{gsub(/\//, "_"); gsub(/-/, "_")}1' 

You really, really, really, (emphasis on "really") do not want to use something like sed -i to edit the files "in-place". (I put "in-place" in quotes, because gnu's sed does not edit the files in place, but creates new files with the same name.) Doing so is a recipe for data corruption, and if you have a lot of files you don't want to take that risk. Just write the files into a new directory tree. It will make recovery much simpler.

eg:

d=backup/$(dirname "$filename")
mkdir -p "$d"
awk '...' "$filename" > "$d/$filename"

Consider if you used something like -i which puts backup files in the same directory structure. If you're modifying files in bulk and the process is stopped half-way through, how do you recover? If you are putting output into a separate tree, recovery is trivial. Your original files are untouched and pristine, and there are no concerns if your filtering process is terminated prematurely or inadvertently run multiple times. sed -i is a plague on humanity and should never be used. Don't spread the plague.

William Pursell
  • 204,365
  • 48
  • 270
  • 300