Caspertijmen1
Caspertijmen1

Reputation: 371

Bash - how to replace nth string on mth line in a file?

I have an input script containing many random seeds. I want create a bash script that constantly runs my script, creates new random seeds, runs the script etc. I know the locations of the random seeds, e.g. this is the 8th line:

create_atoms 1 random 650 923456 t

Now I would want to replace 923456 to my previously declared variable. I guess I should use something like

sed -i '8s/923456/$Var/' file

But I can't figure out the specifics.

Upvotes: 0

Views: 56

Answers (2)

Socowi
Socowi

Reputation: 27360

To replace the 5th word in the 8th line with GNU sed use

sed -E "8s/[^ ]+/$var/5"

For posix sed use

sed -E "8s/([^ ]+ +){4}([^ ]+)/\1$var/"

Note that $var must be free of special symbols like /, \, and & in both cases.

Upvotes: 1

karakfa
karakfa

Reputation: 67567

$ awk -v line=8 -v word=5 -v value="$Var" 'NR==line{$word=value}1' file

Upvotes: 3

Related Questions