0

Can I able to give the value(32) in the form of variable in the below awk command instead of hardcoding 32 directly?

df -h | head -1|awk '{printf "%s%32s",$1,$2}'

I tried like awk -v var=32 but its not working.

Can anyone suggest me please.

Peter.Fox
  • 55
  • 1
  • 1
  • 6
  • 2
    `its not working` is one of the worst failure descriptions you could give, usually eliciting groans from everyone reading it. Never just say `it's not working` - tell us in what way it's not working. Syntax error, wrong output, no output, core dump, something else? And show us exactly the script you ran that failed, don't just show the start of it - we've no idea what you did with `var` after you initialized it so we can't tell you where you went wrong. – Ed Morton Jul 19 '18 at 13:50
  • 2
    Possible duplicate of [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – Tom Fenech Jul 19 '18 at 13:52
  • 4
    He's not using a shell variable and he's doing the right thing to pass the shell value to an awk script, it's whatever he's doing with that variable that's the issue and he hasn't shown us that code yet. I suspect the question is how to use an awk variable in the printf formatting string rather than how to use a shell variable. – Ed Morton Jul 19 '18 at 13:52

3 Answers3

5
awk -v var=32 '{printf "%s%*s\n", $1, var, $2}'
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    Thanks a lot Morton,. Its working in Linux but the same when tried on Solaris I'm getting error. May I know the reason? – Peter.Fox Jul 19 '18 at 15:01
  • 1
    The default awk on Solaris is old, broken awk (aka "oawk") which must never be used because it's, well, old and broken. On Solaris use /usr/xpg4/bin/awk instead of the default one (which is in /bin or /usr/bin, I don't remember) as that's the closest to a modern POSIX awk. Do not be tempted to use New AWK aka `nawk` as it's only "new" in relation to "oawk". nawk is itself very old and lacking POSIX functionality. – Ed Morton Jul 19 '18 at 15:10
1
awk -v var=32 '{printf "%s%"var"s", $1,$2}'

Note: The solution of Ed Morton is cleaner as it does not use AWK string concatenations but makes direct use of the printf formatting

Simultaneously, if you want to get rid of your head then you can combine everything as:

$ df -h | awk -v var=32 '{printf "%s%"var"s", $1,$2; exit}'
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

One alternative to the answer given by Ed Morton, could be useful, if you have the number already stored in an environment variable (say: FIELD_WIDTH). In this case,

df -h | head -1|awk '{printf "%s%" ENVIRON["FIELD_WIDTH"] "s",$1,$2}'

would do the job.

UPDATE:

You should also get rid of the head:

df -h | awk 'NR==1 {printf "%s%" ENVIRON["FIELD_WIDTH"] "s",$1,$2}'
user1934428
  • 19,864
  • 7
  • 42
  • 87