I'm trying to assign the output of a command to a variable and then concat it with another string, however, it keeps overwriting the original string instead of adding on to the end of the string.
Contents of test.txt --> This is a test
var1="`head -n 1 test.txt`"
echo $var1 (This is a test)
var1=$var1"123"
echo $var1 (123s is a test [instead of: This is a test123)
The issue has something to do with the first line. If I simply assign a string like this:
var1="This is a test" , then it all works, but when I try to assign the output of a command to a variable, it does not add to the string properly.
/tmp$ cat test.txt
This is a test
This is also a test
/tmp$ var1="`head -n 1 test.txt`"
/tmp$ echo $var1
This is a test
/tmp$ var1=${var1}123
/tmp$ echo $var1
This is a test123
/tmp$
I agree there, but I used the back-quotes as that's what the OP used while asking the question. You *can* nest commands using backquotes as well, but the number of escape chars would increase with every level.
blowtorch - I tried the code you have given, but ended up with the same result --> 123s is a test
I am using Korn Shell which comes with the Microsoft Services for Unix Applications (SUA) add on component to Windows Server 2003 R2.
Is there a command which I can use to insert a string into the other string - either in the middle or at the end? For example, it would count the number of characters in "This is a test" and then append after then 14th character.
As always, with these types of problems, it was some minor annoyance that was causing it - a carriage return/line feed in the test.txt file after the string.
If I do a wc -c on the file it would give me 16 instead of 14 (2 extra for the CRLF).
Thanks for your help!
I've changed my code to use the var1=${var1}123 (thanks blowtorch) notation and also the var1=$(<test.txt) (thanks macosta) notation, which looks cleaner.