How can I use a variable with sgrep in a script?

0
1
Asked By TechieTurtle47 On

I'm trying to use the `sgrep` command in a script to search for a variable string that I read from standard input. The command I have works for a hard-coded string like `emdash`, but when I replace it with a variable after reading input with `read sym`, it doesn't return any results. For example, my original command looks like this:

```
sgrep -o '%rn' '""" _quote_ """ in ("name[Group1]" .. "n" in outer("{" .. "}" containing "emdash"))' /usr/share/X11/xkb/symbols/??
```

But when I try to use `$sym` in place of `emdash`, like this:

```
containing "$sym"
```

It returns nothing. I tried removing the quotes and using `containing "$sym"`, but that leads to a parse error. I also tried `containing "$(echo $sym)"`, with no success. So, can `sgrep` evaluate variables at all? What am I doing wrong?

1 Answer

Answered By ScriptSavant92 On

In bash, anything inside single quotes is treated as a literal string, which means variables won't be evaluated. You need to break the quotes and include the variable outside of them. Instead, try this format:

```
sgrep -o '%rn' '""" _quote_ """ in ("name[Group1]" .. "n" in outer("{" .. "}" containing "'"$sym"'"))' /usr/share/X11/xkb/symbols/??
```

This way, you're still treating `$sym` as a variable while keeping the necessary quotes around it. Alternatively, you could consider using a simplified `sgrep` setup to avoid this level of complexity.

CodedPenguin18 -

An alternative method is to set up your script like this:

```bash
#!/usr/bin/env bash

arg1="$1"
symbol="${arg1:-emdash}"

sgrep_args=(
-p "m4 -D __SYMBOL__='$symbol'"
-e '""" _quote_ """ in ("name[Group1]" .. "n" in outer("{" .. "}" containing "__SYMBOL__"))'
-o '%rn'
)

sgrep "${sgrep_args[@]}" /usr/share/X11/xkb/symbols/??
```

This way, you're allowing for more manageability with variables.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.