awkの変数内の文字をエスケープする方法は?

awkの変数内の文字をエスケープする方法は?

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

おすすめ記事