2

I'm trying to replace a string using AWK pipe out to SED

grep pdo_user /html/data/_default_/configs/application.ini | awk '{print $3}' | sed -i 's/$1/"username"/g' /html/data/_default_/configs/application.ini

but found string is not replaced

Output for

grep pdo_user /html/data/_default_/configs/application.ini | awk '{print $3}'

is

"root"

Any tips on that?

JackTheKnife
  • 3,795
  • 8
  • 57
  • 117
  • See: [Difference between single and double quotes in Bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Nov 10 '16 at 20:13
  • But `$3` from `AWK` is a string `"root"` which I need to replace each time with `"username"` – JackTheKnife Nov 10 '16 at 20:14
  • 2
    I suggest to replace `'s/$1/"username"/g'` by `'s/'"$1"'/"username"/g'`. `$1` should not contain any special characters that sed could interpret as commands. – Cyrus Nov 10 '16 at 20:17
  • Still `$1` is not passed to sed – JackTheKnife Nov 10 '16 at 20:18
  • Please add output of `grep pdo_user /html/data/_default_/configs/application.ini | awk '{print $3}'` and `echo "$1"` to your question. – Cyrus Nov 10 '16 at 20:20
  • OP updated with grep to awk piping output – JackTheKnife Nov 10 '16 at 20:26
  • Remove last `/html/data/_default_/configs/application.ini` from your command line. Output should show `"username"`. – Cyrus Nov 10 '16 at 20:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127838/discussion-between-jacktheknife-and-cyrus). – JackTheKnife Nov 10 '16 at 20:30
  • 3
    I think you want something like `sed 's/'$(awk '/pdo_user/{print $3}' /path/to/application.ini)'/"username"/' /path/to/application.ini` ? Good luck. – shellter Nov 10 '16 at 21:02
  • @JackTheKnife: Do you want to replace in every line which contains somewhere `pdo_user` string `root` in column three by string `username`?. – Cyrus Nov 10 '16 at 21:45
  • 1
    @Cyrus Correct - I'm searching for `pdo_user` which contains some string at 3r position (in this case string is `"root"`) and I want to replace that string with `"username"` (both strings contains double quotations) – JackTheKnife Nov 10 '16 at 21:53

2 Answers2

2

I suggest to use awk and mv:

awk '/pdo_user/ && $3=="\"root\"" {$3="\"username\""}1' /path/to/application.ini > /path/to/application.tmp
mv /path/to/application.tmp /path/to/application.ini
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • But `pdo_user` may be different than `"root"` which was only in my case but example is good enough to replace without the statement `&& $3=="\"root\""` – JackTheKnife Nov 11 '16 at 13:58
1

Working solution based on Shelter's tip using AWK and SED

sed -i 's/'$(awk '/pdo_user/{print $3}' /path/to/application.ini)'/"username"/' /path/to/application.ini
JackTheKnife
  • 3,795
  • 8
  • 57
  • 117