5

I have a file which contains only one line

$> cat file.txt
apple,orange,cat,dog

I need to append two String to it and assign it to a variable, one in front and another in the end, so that it becomes:

var=key,apple,orange,cat,dog,ending

so that I can use the $var somewhere else...

May I know how could I do that in bash script? Or any linux command can do that? Thanks.

FGH
  • 51
  • 1
  • 1
  • 2

2 Answers2

8

One way would be this:

var="key,$(<file.txt),ending"
garyjohn
  • 36,494
2

One possible solution is:

var=$(echo -n 'key,' && cat file.txt | tr '\n' ',' && echo 'ending')
  • $(...) gets the output string of the commands in ...
  • echo -n prints the following string without a trailing newline
  • cat prints the file's contents and tr '\n' ',' replaces the trailing newline with a comma
  • echo prints the following string with newline (which is not really important)
Tim
  • 2,202