执行含多引号的远程SSH命令时遇awk语法错误求助
Hey there, let's walk through what's causing that syntax error and fix up your command properly.
What's Going Wrong
Shell is eating your awk field references
You wrapped the entire ssh command in double quotes, so your shell is interpreting$2and$5as shell variables (not awk's field identifiers). If those variables aren't defined in your shell, they get replaced with empty strings—leaving awk withprint ,open_, which is invalid syntax.Missing input file for grep
Yourgrep -i 20-10-2018doesn't specify which file to search. It's waiting for input from stdin instead of readingresult.csvdirectly.Syntax mistake in the while loop
Thewhile read line dopart is missing a semicolon (or newline) betweenlineanddo—shell syntax requires a separator there.Undefined
$Datevariable
Unless you've explicitly set aDatevariable in your shell,$Datewill output nothing. You should use thedatecommand to get the current date instead.
Fixed Command
Here's the corrected version that addresses all these issues:
ssh "$ip_address" "grep -i 20-10-2018 result.csv | awk -F ',' '{print \$2\",open_\"\$5}'" | while read line; do echo "$(date +%Y-%m-%d):00:00,$line"; done
Key Fixes Explained
- Escaped awk fields: We added backslashes to
\$2and\$5so the shell passes them through to awk instead of trying to expand them. Alternatively, you could wrap the awk script in single quotes entirely (which is often cleaner):ssh "$ip_address" "grep -i 20-10-2018 result.csv | awk -F ',' '\''{print $2",open_"$5}'\''" - Moved
result.csvto grep: Now grep reads directly from the file instead of waiting for input. - Fixed while loop syntax: Added a semicolon
;betweenlineanddo. - Replaced
$Datewithdatecommand:$(date +%Y-%m-%d)generates a properly formatted date (adjust the format string like%d-%m-%Yif you need day-month-year instead).
Bonus: More Efficient Version
You can combine grep and awk into a single command to avoid extra pipe overhead:
ssh "$ip_address" "awk -F ',' '/20-10-2018/i {print \$2\",open_\"\$5}' result.csv" | while read line; do echo "$(date +%Y-%m-%d):00:00,$line"; done
The /20-10-2018/i in awk does the same case-insensitive match as your grep command.
内容的提问来源于stack exchange,提问作者KaverappaKU

