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)

  • 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. – 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 0:05

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
  • 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

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.

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