how to write result of this command "echo "12:23:34" awk '{print $2}'" to variable in bash
- User
how to write result of this command "echo "12:23:34" | awk '{print $2}'" to variable in bash
- Assistant
The command you provided,
echo "12:23:34" | awk '{print $2}', will not output anything as there is only one field$1and you are trying to print the second field$2which does not exist. The output of this command will actually be empty.However, if you want to assume that "12:23:34" is the field you want to capture into a variable, you should use
$1inawkinstead which represents the first (and in this case, the only) field. To capture the output into a variable in Bash, you would use command substitution as follows:bashvariable=$(echo "12:23:34" | awk '{print $1}')If you indeed have multiple fields and want to capture the second one, you should provide an input string with fields separated by whitespace (default field separator in
awk). For example:bash# Multiple fields separated by space, fetching the second one input="some_text 12:23:34 other_text" variable=$(echo "$input" | awk '{print $2}')