LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Sed: assigning its output to a variable. (https://www.linuxquestions.org/questions/linux-newbie-8/sed-assigning-its-output-to-a-variable-860606/)

stf92 02-03-2011 10:41 PM

Sed: assigning its output to a variable.
 
Kernel 2.6.21.5, GNU/Linux (Slackware 12.0).

Hi:
In this script,
Code:

semoi@darkstar:~$ cat rename4.sh
#!/bin/bash

INPUT="k3b_audio_0_04"
echo $INPUT | sed s/k3b_audio_0_// > OUTPUT
echo "Input=  $INPUT"
echo "Output= $OUTPUT"
semoi@darkstar:~$

I would like the output to be
Code:

$ Input=  k3b_audio_0_04
$ Output= 04

But how do I send sed's output into OUTPUT? Regards.

EDIT: I found it:
OUTPUT=$(echo $INPUT | sed s/k3b_audio_0_//)

lucmove 02-03-2011 10:52 PM

Code:

semoi@darkstar:~$ cat rename4.sh
#!/bin/bash

INPUT="k3b_audio_0_04"
OUTPUT=$(echo $INPUT | sed s/k3b_audio_0_//)
echo "Input=  $INPUT"
echo "Output= $OUTPUT"

You can also do this:

Code:

OUTPUT=`echo $INPUT | sed s/k3b_audio_0_//`
But backticks make the code look kind of "dirty", are much harder to escape if the code inside them also contains backticks, and they are not a subshell. The $(CODE) format is a lot cleaner, embeddable and it creates a subshell.

stf92 02-04-2011 12:04 AM

Yes. As you can see, I had figured out a way out minutes before you pressed 'Submit Reply'. The second form I'll bear it in mind, and the morals behind it. Thanks a lot.

grail 02-04-2011 12:38 AM

Or in this case you could have just used parameter substitution:
Code:

OUTPUT=${INPUT##*_}


All times are GMT -5. The time now is 11:23 PM.