[英]Glob string stored in a variable is not expanded when used in a command
[英]How to make a '$N' within a string variable in a bash script be used as a operator in awk command when variable is expanded?
因此,由於建議,我會嘗試更簡潔。
#!/bin/env bash
out1='$3 ~ "RB"'
out2='&& $3 ~ "F[0-9]"'
out3='&& $3 ~ /H*TF/'
printing=''"\t"'$3'
awk_output=$(awk -F, -v o1="$out1" -v o2="$out2" -v o3="$out3" -v p1="$printing" \
'o1 o2 o3 { print NR,p1}' test.csv)
dialog --title "title" \
--msgbox "$awk_output" 0 0
上面的代碼是我正在嘗試編寫的一個小程序的示例,它需要一些用戶選擇的變量,頂部的輸出和打印變量。 並使用這些對數據庫進行 awk 查詢。
問題是傳遞的變量字符串包含一個 '$3' 作為示例。 我希望將其讀取為 awk 中的字段運算符,因為它通常是,但它被讀取為文字字符串。 因此,在打印時,awk 打印文字“$3”而不是它應該在 csv 文件中表示的字段。 我也嘗試過 ENVIRON 和 SYMTAB,但收效甚微。 以前有沒有人遇到過這種類型的事情? 謝謝,希望它也更簡潔一點。
jsut澄清output目前是這樣的:
1 $3
2 $3
3 $3
4 $3
5 $3
我希望“$3”實際上代表 awk 命令中 csv 文件的一個字段。 像這樣的東西是我想要得到的
1 "info from 3rd field in csv"
2 "info from 3rd field in csv"
3 "info from 3rd field in csv"
4 "info from 3rd field in csv"
5 "info from 3rd field in csv"
我希望將其讀取為 awk 中的字段運算符,因為它通常是,但它被讀取為文字字符串
所以將它作為命令的一部分傳遞,而不是作為變量傳遞......
printing='$3'
awk -F, -v OFS='\t' "$out1 $out2 $out3 { print NR, $printing}" test.csv
使用set -x
調試 shell 腳本。 請務必閱讀 shell 中單引號和雙引號之間的區別以及擴展是如何發生的。
A simpler approach is, rather than pass all the shell variables with special characters to awk
, we can use printf
to build the awk
command and then use eval
to execute and store the output.
修改腳本:
#!/bin/env bash
out1='$3 ~ "RB"'
out2='&& $3 ~ "F[0-9]"'
out3='&& $3 ~ /H*TF/'
printing='"\t"$3'
printf -v cmd $'awk -F, \'%s %s %s {print NR, %s}\'' "$out1" "$out2" "$out3" "$printing"
awk_output=$(eval "$cmd" test.csv)
dialog --title "title" \
--msgbox "$awk_output" 0 0
解釋:
printing='"\t"$3'
。 這就是在 output 中打印標簽所需的全部內容printf -v cmd $'awk -F, \'%s %s %s {print NR, %s}\'' "$out1" "$out2" "$out3" "$printing"
%s
占位符awk -F, ...
前面的$
。 這是因為 awk 字符串包含'
。 要使用文字'
,我們需要在字符串之前添加$
。CSV 使用:
apple,orange,RBF1HTF
apple,orange,RBF2HTF
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.