我正在尝试制作一个脚本,使用 awk 从 .config/okularrc 获取最近的文件名并将它们通过管道传输到 dmenu,然后返回 awk 以获取所选名称的路径。但是,我收到一个错误,告诉我在正则表达式中应该转义一个字符。
Okularrc 文件:
[Recent Files]
File1[$e]=$HOME/documents/med/oh/OH Lecture (12)_Lead Poisoning Summary.pdf
File2[$e]=$HOME/ug/Biochemistry/1. biochemistry of kidney.pdf
File3[$e]=$HOME/ug/Archives/3. UG-(mid+final)-WAREED.pdf
File4[$e]=$HOME/ug/Biochemistry/1. b)iochemistry of kidney.pdf
Name1[$e]=OH Lecture (12)_Lead Poisoning Summary.pdf
Name2[$e]=1. biochemistry of kidney.pdf
Name3[$e]=3. UG-(mid+final)-WAREED.pdf
Name4[$e]=1. b)iochemistry of kidney.pdf
我制作的脚本:
#!/bin/bash
DEBUG=1
# Get the names of the files
names=$(awk -F'=' '/^Name/{print $2} ' ~/.config/okularrc)
[ $DEBUG == 1 ] && echo -e "[*] Names are:\n$names\n"
# Pass the names to dmenu and select a file
selected_name=$(echo "$names" | dmenu -l 10 -i -p "Select a recent file:")
[ $DEBUG == 1 ] && echo -e "[*] Selected name is:\n$selected_name\n"
# Get the path of the selected file
file_path=$(awk -v name="$selected_name" -F'=' '$2 ~ name "$" && /^File/ {print $2}' ~/.config/okularrc)
[ $DEBUG == 1 ] && echo -e "[*] File path is:\n${file_path}\n"
# Run Okular with the path of the file
okular "${file_path/'$HOME'/$HOME}"
# If history is zero just start okular; TODO add browser
#[ -z $names ] && okular && exit
当我在具有“(”的文件上运行此命令时,它会给出以下输出:
[*] Names are:
1. b(iochemistry of kidney.pdf
[*] Selected name is:
1. b(iochemistry of kidney.pdf
awk: cmd. line:1: (FILENAME=/home/anonymous/.config/okularrc FNR=1) fatal: invalid regexp: Unmatched ( or \(: /1. b(iochemistry of kidney.pdf$/
[*] File path is:
我是 awk 的新手,我想了解更多信息,非常感谢您的帮助
答案1
替换了这一行:
file_path=$(awk -v name="$selected_name" -F'=' '$2 ~ name "$" && /^File/ {print $2}' ~/.config/okularrc)
用这一行:
file_path=$(awk -v name="$selected_name" -F'=' 'index($2,name) && /^File/ {print $2}' ~/.config/okularrc)
致谢@steeldriver