i have two variables (txt and a line number) i want to insert my txt in the x line
card=$(shuf -n1 shuffle.txt)
i=$(shuf -i1-52 -n1)
'card' is my txt : a card randomly selected in a shuffle 'deck' and i want to insert it at a random line (i)
i have two variables (txt and a line number) i want to insert my txt in the x line
card=$(shuf -n1 shuffle.txt)
i=$(shuf -i1-52 -n1)
'card' is my txt : a card randomly selected in a shuffle 'deck' and i want to insert it at a random line (i)
Using a file as your data structure is going to incur some heavy performance penalties on your application, but you can insert the contents of variable foo at line number i in file.txt as follows:
printf '%s\n' "${i}i" "$foo" . x | ex file.txt
If the variable foo contains newlines this has some edge cases, but otherwise it will work regardless of any special characters, etc., providing only that the variable i has a valid line number (i.e. it can't be greater than the number of lines in file.txt).
But, again, using line numbers of files as your data structure is a horribly inefficient way to shuffle a deck of cards. So beware.
Given that txt is assigned to the text you wish to add, and that i is assigned to the line number at which to insert the text, this will output what is desired:
$ awk -v line="$i" -v text="$txt" '{print} NR==line{print text}' /path/to/textfile
A slight modification to add text to the specified line number (in addition to the text already there), rather than add it after the existing line i (on a line by its own) as the code above does:
$ awk -v line="$i" -v text="$txt" ' NR!=line{print} NR==line{print $0 text}' /path/to/textfile
txt at the line number in question, not insert it. (It will be on a line by itself, but its line number will be i+1, not i.)
– Wildcard
Jan 29 '18 at 21:38