Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

One way would be this:

var="key,$(<file.txt),ending"
share|improve this answer

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)
share|improve this answer
    
It doesn't work... would you please advise if I've done something wrong? As the follow: var=$(echo -n 'KEY,' && cat header-cp-match-src-file.csv | tr '\n' ',' && echo 'ID_BB_COMPANY,BB_CONAME,ID_BB_PARENT_CO,LONG_PARENT_COMP_NAME,COMPANY_CORP_TICK‌​ER,AVG_SIM_SCORE') –  FGH Oct 25 '13 at 21:21
    
How should I know if you are doing something wrong, if you do not even post the contents of $var. I suggest you first try with your sample file and specifications from your question and test, if this gives the desired result. Then try with your original data and strings. –  Tim Oct 25 '13 at 21:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.