Without further information, the following awk
program should work:
awk -v where="$line" -v what="$substitute" 'FNR==where {print what; next} 1' file.txt
- It will import the shell variables
$line
and $substitute
into awk
variables where
and what
.
- When processing the file, it will by default simply print the current line ( the seemingly stray
1
outside the rule block { ... }
).
- When the per-file line counter
FNR
is equal to the line number stored in where
, we print the substitute string what
instead, and skip execution to the next input line.
Note that awk
doesn't edit files in-place, so you have to redirect the output and rename the result file once you are satisfied. Alternatively, with sufficiently new versions of GNU awk
, you can use the -i inplace
option to modify the file in-place.
Note that (as pointed out by αғsнιη/Stéphane Chazelas/Ed Morton) the above will show erratic behavior if your substitute
string contains the literal \
, since this method expands escape sequences. In that case, the awk
-based alternative solution in Stéphane Chazelas' answer with exporting the variable and referencing it as ENVIRON["substitute"]
would do the trick (see this answer for more information).