Home > other >  How to prepend to a string that comes out of a pipe
How to prepend to a string that comes out of a pipe

Time:01-09

I have two strings saved in a bash variable delimited by :. I want to get extract the second string, prepend that with THIS_VAR= and append it to a file named saved.txt

For example if myVar="abc:pqr", THIS_VAR=pqr should be appended to saved.txt.

This is what I have so far,

myVar="abc:pqr"
echo $myVar | cut -d ':' -f 2  >> saved.txt

How do I prepend THIS_VAR=?

CodePudding user response:

printf 'THIS_VAR=%q\n' "${myVar#*:}"

See Shell Parameter Expansion and run help printf.

CodePudding user response:

The more general solution in addition to @konsolebox's answer is piping into a compound statement, where you can perform arbitrary operations:

echo This is in the middle | {
    echo This is first
    cat
    echo This is last
}
  •  Tags:  
  • Related