0

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)

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Larotule
  • 13
  • 2
  • 3
    Just a tip: if your purpose is just to learn Bash that's fine (although there are better projects to sharpen your shell knowledge), but if your purpose is to make a functional card game, even just a toy one for your own use, I *strongly* recommend you use a different language than the shell. [Shells are for *orchestration,* not really for programming.](https://unix.stackexchange.com/a/303387/135943) – Wildcard Jan 29 '18 at 21:30
  • Yeah i need to learn something better because "graphics" are awfull, i use unicode for cards lol... it just a memory training tool, learn the deck then move a random card and find it – Larotule Jan 30 '18 at 00:05

2 Answers2

0

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.

Wildcard
  • 35,316
  • 26
  • 130
  • 258
0

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
Wildcard
  • 35,316
  • 26
  • 130
  • 258
DopeGhoti
  • 73,792
  • 8
  • 97
  • 133
  • Strictly speaking, that will *append* `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
  • Fair point. Alternate take added which will append, rather than insert. – DopeGhoti Jan 29 '18 at 21:41