I have 2 files, one with list of text files and the other with content I want to add.

I can't seem to be able to use the variable in a bash script.

the script is like this:

for name in $(cat /home/stuff/list)
  keysss=`cat /home/stuff/test`
  sed -i "27i $keysss " $name

This way it gives an error. Other ways I've tried print the word but I want to print the content of it into file

ps. the files contain ca root certificates

  • Try sed -i "s/27i/$keysss/g" <- The " are to be exchanged with ' if you don't want $keysss to be parsed as variable. – ADDB Jun 22 '17 at 11:34
  • i need to parse it as variable, that's the issue i dont't want to print $keysss but the content of that file – Vitalik Jimbei Jun 22 '17 at 11:39
  • tested some more, it's not possible when the "test" file is filled with a root certificate, regex from sed reads it improperly for this command to work. – Vitalik Jimbei Jun 23 '17 at 8:39
  • Useless use of backticks. – David Foerster Nov 16 '17 at 11:45

Instead of reading the file into a variable and inserting that content with i command (which will fail for certain cases like the fail containing newlines/they would need to get escaped), you should use the r command to append the text directly:

for name in $(cat /home/stuff/list); do 
  sed -i "27r /home/stuff/test" $name

To avoid the issues with backticks it would be better to use:

while read -r name; do 
  sed -i "27r /home/stuff/test" "$name"
done < /home/stuff/list

Or more simply:

xargs -rd '\n' -- sed -i "27r /home/stuff/test" < /home/stuff/list
  • Two (now deleted) answers suggested the same thing. – muru Aug 24 '17 at 6:31
  • What are you trying to tell me? I didn't copy my answer. I don't even remember other answers being given. – Philippos Aug 24 '17 at 6:47
  • Oh, I wasn't implying you copied (FWIW, I upvoted this answer). It just amused me that two users suggested the same thing a month ago, then deleted their answers, then you came along and also suggest r. History repeating? i.stack.imgur.com/cWM5G.png – muru Aug 24 '17 at 6:52
  • I see. Well, r is the obvious solution for this. I just wonder why the others did delete their correct answers. And whether the OP cares at all. – Philippos Aug 24 '17 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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