LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   problem with $HOME and awk (https://www.linuxquestions.org/questions/programming-9/problem-with-%24home-and-awk-4175416903/)

patrick295767 07-15-2012 11:51 PM

problem with $HOME and awk
 
Hi,

Suprinsingly the two codes differs in output :( (??)
echo '$HOME/fileb.txt' > "$HOME/file.ini"

Code:

        head -n 1 "$HOME/file.ini"  |    awk -v vk="$HOME" ' {  gsub("\$HOME",vk) ; print $0 }  '

Code:

       
                var=` head -n 1 "$HOME/file.ini" |    awk -v vk="$HOME" ' {  gsub("\$HOME",vk) ; print $0 }  ' `
echo $var


grail 07-16-2012 01:36 AM

Well as you included no input or output, it will be difficult to test / see the difference?

I would however urge you to use $() over `` when issuing more complex substitutions.

patrick295767 07-16-2012 11:45 PM

Quote:

Originally Posted by grail (Post 4729207)
Well as you included no input or output, it will be difficult to test / see the difference?

I would however urge you to use $() over `` when issuing more complex substitutions.

with `` it returns $HOME/ bla bla

with $() it returns /home/peterba/file.ini

why so big difference? why is it like that?

grail 07-17-2012 03:08 AM

You still have not indicated what is in file.ini, or at least what the first line might actually be.
Currently the code looks pointless without anymore information. Maybe you could actually advise what it is you are trying to achieve?

pan64 07-17-2012 04:00 AM

the problem is the quote evaluation, in the second case there is one more level of quotes (backtick) which will modify how the "program" will be seen during execution.

Kenhelm 07-17-2012 04:59 AM

Quote:

Code:

var=` head -n 1 "$HOME/file.ini" | awk -v vk="$HOME" ' {  gsub("\$HOME",vk) ; print $0 }  ' `

The backslash could be causing the different output.

Why is $(...) preferred over `...` (backticks)?
http://mywiki.wooledge.org/BashFAQ/082
Quote:

`...` is the legacy syntax required by only the very oldest of non-POSIX-compatible bourne-shells. There are several reasons to always prefer the $(...) syntax:

Important differences
Backslashes (\) inside backticks are handled in a non-obvious manner:
Code:

  $ echo "`echo \\a`" "$(echo \\a)"
  a \a
  $ echo "`echo \\\\a`" "$(echo \\\\a)"
  \a \\a
  # Note that this is true for *single quotes* too!
  $ foo=`echo '\\'`; bar=$(echo '\\'); echo "foo is $foo, bar is $bar"
  foo is \, bar is \\


Code:

echo  "`echo "\$HOME"`"
/home/kenhelm

echo "$(echo "\$HOME")"
$HOME


AnanthaP 07-17-2012 05:12 AM

What does awk return?


All times are GMT -5. The time now is 02:10 PM.