0

I am trying to use sed to use as input for a variable. The user will choose from a list of files that have numbers before each to identify individual files. Then they choose a number corresponding to a name. I need to get the name of that file. My code is:

for entry in *; do
((i++))
echo "$i) $entry: "
done

echo What file # do you want to choose?:
read filenum
fileName=$(./myscript.sh | sed -n "${filenum}p")
echo $fileName  ###this is to see if anything goes into fileName. nothing is ever output
echo What do you want to do with $fileName?

Ideally I would use () instead of the backtick but I can't seem to figure out how. I've looked at the links below, but can't get those ideas to work. I believe a problem may be that I am trying to include the filenum variable inside my sed.

https://www.linuxquestions.org/questions/linux-newbie-8/storing-output-of-sed-in-a-variable-in-shell-script-499997/

Store output of sed into a variable

  • search here for `[bash] select done` and read the bash manual (on-line) about the `select` command. https://stackoverflow.com/questions/64130687/bash-nested-select-menu-only-first-selection-works-the-second-selection-doesn/64137802#64137802 was a very good example that came up just recently. Good luck. – shellter Oct 16 '20 at 00:54
  • You shouldn't have backticks around `$filenum` – Barmar Oct 16 '20 at 00:57
  • If I remove the backticks around $filenum then the output becomes - sed: 1: "2": command expected – contactme8359 Oct 16 '20 at 01:02
  • Of course. The command to print line 2 is `2p`, not just `2`. – Barmar Oct 16 '20 at 01:02
  • Why are you printing a line of a shell script? Did you really mean to print a selected line of the output of the script? – Barmar Oct 16 '20 at 01:03
  • That sed command is even shown in the question you linked to. – Barmar Oct 16 '20 at 01:05
  • If you quote your strings, things are much simpler, `echo "$i) $entry: "` – David C. Rankin Oct 16 '20 at 01:37

1 Answers1

1

Don't put backticks around $filenum. That will try to execute the contents of $filenum as a command. Put variables inside double quotes.

And if you do want to nest a backtick expression inside another set of backticks, you have to escape them. That's where $() becomes useful -- they nest without any hassle.

When you use sed -n, you need to use the p command to print the lines that you want to show in the output.

fileName=$(sed -n "${filenum}p" myscript.sh)

This will put the contents of line $filenum of myscript.sh in the variable.

If you actually wanted to execute myscript.sh and print the selected line of its output, you need to pipe to sed:

fileName=$(./myscript.sh | sed -n "${filenum}p")
Barmar
  • 741,623
  • 53
  • 500
  • 612