4

This post explains how to add a line at the beginning of a file from the terminal. But how do I modify from the terminal a line somewhere in a file if I do not know which line it is?

I should modify the line eni=10.*10**9 to eni=10.*10**8 note the exponents. It is the second time that eni appears

Kulfy
  • 18,154
mattiav27
  • 927
  • 1
  • 9
  • 27

3 Answers3

4

I think this is what you want:

line=$(grep -n -m2 "eni" file | tail -n1 | cut -f1 -d:)

sed -i $line's/9$/8/' file
4

Since Ubuntu now ships with GNU Awk v4.0+ (which provides an inplace module) you could do something like

gawk -i inplace '/eni=/ {if (++c == 2) sub(/10\*\*9/,"10**8")} 1' file

You can make the regular expressions /eni=/ and/or /10\*\*9/ more or less specific as required.

Similarly in perl

perl -i -pe 'if (/eni=/) {s/10\*\*9/10\*\*8/ if (++$c == 2)}' file
steeldriver
  • 142,475
3

Using sed:

sed -i ': 1 ; N ; $!b1 ; s/eni\=10\.\*10\*\*9/eni\=10\.\*10\*\*8/2' filename

/ is one of the delimiters and \ is the escape character. \ is used so that bash won't interpret special characters as some command, like * as wildcard.

Kulfy
  • 18,154