I need some help . I have this command
df -h | awk '/md2/' | awk '{print $5}'
I want "/md2/" to set it in variable . search="/md2/" using
df -h | awk '$search' | awk '{print $5}'
gives me no response, how can I make this.
Use:
search='md2'
df -h | awk -v x="$search" '$0~x{print $5}'
How it works:
-v x="$search"
This tells awk to define an awk variable x to have the value of $search.
$0~x{print $5}
$0 ~ x tells awk to select lines that match the regex in variable x. For the selected lines, field 5 is printed.
df -h | awk '$search' | awk '{print $5}'
The above won't work because $search is inside single-quotes and that stops bash from substituting in for the value of $search. You can see this with:
$ search='/md2/'; echo awk '$search'
awk $search
The following will work:
search='/md2/'
df -h | awk "$search" | awk '{print $5}'
Here, $search is inside double-quotes and bash will expand variables that are in double-quotes.
There are still two issues with this:
awk "$search" is potentially dangerous. Awk will execute whatever the contents of $search are. Unless you are very sure about what the contents will be, this could result in mangled or deleted files, etc.
Two uses of awk are unnecessary and slow. Both actions, selecting a line and printing a field can be done in one invocation of awk.