0

I'm beginner in Bash Scripting and I need to assign to a variable a custom command output,not the entire command just a part of it.Is there a way I can do that?
The command:

gtf 1600 720 60

The Output:

# 1600x720 @ 60.00 Hz (GTF) hsync: 44.76 kHz; pclk: 93.10 MHz
  Modeline "1600x720_60.00"  93.10  1600 1672 1840 2080  720 721 724 746  -HSync +Vsync

What I want to store:

"1600x720_60.00"  93.10  1600 1672 1840 2080  720 721 724 746  -HSync +Vsync
  • 1
    What exactly do you want to store in the variable? I assume it is the output of the command in my answer. – Jindra Helcl Aug 11 '21 at 11:45
  • I want to store from this output 1600x720 @ 60.00 Hz (GTF) hsync: 44.76 kHz; pclk: 93.10 MHz Modeline "1600x720_60.00" 93.10 1600 1672 1840 2080 720 721 724 746 -HSync +Vsync this "1600x720_60.00" 93.10 1600 1672 1840 2080 720 721 724 746 -HSync +Vsync – AlexandruWorld Aug 11 '21 at 11:48
  • 1
    You can use the backtick/subshell syntax from my answer. Just send the output of the command via pipe (`|`) to the sed command, e.g. `your_command | sed 's/^.*Modeline //'` If the command writes the output to `stderr`, be sure to redirect first: `your_command 2>&1` – Jindra Helcl Aug 11 '21 at 11:50
  • You can improve your question by adding the command you are running, its output, and the relevant part of the output that you want to store in the variable. – Jindra Helcl Aug 11 '21 at 11:55
  • @AlexandruWorld : So you also want to catch the last line of the output without the word _Modeline_? Or was this just an example, and the format can vary? And I guess the output is stdout and not stderr, right? – user1934428 Aug 11 '21 at 12:28
  • Yes the last line without Modeline ,the format can vary and the output is stdout – AlexandruWorld Aug 11 '21 at 12:29

2 Answers2

1

You can enclose your command in backticks to store its output:

a=`echo Hello`

Alternatively, you can also use $():

a=$(echo Hello)

If you want to store only a part of the output, you can pipe the output of your command to a postprocessing script, e.g. sed:

a=$(echo foo | sed 's/foo/bar/')
Jindra Helcl
  • 3,457
  • 1
  • 20
  • 26
0

There are many ways to arrive at your desired output, but I like grep:

gtf 1600 720 60 | grep -Po '(Modeline)\K(.*)'

Here you would be using a regular expression with grep to capture any output on a line that follows "Modeline".

Then you can use command substitution to store the output in a variable:

OUTPUT=$(gtf 1600 720 60 | grep -Po '(Modeline)\K(.*)')

echo "$OUTPUT"
# "1600x720_60.00"  93.10  1600 1672 1840 2080  720 721 724 746  -HSync +Vsync
some coder guy
  • 285
  • 3
  • 10