Home > Blockchain >  How to automatically add many similar lines to a text file?
How to automatically add many similar lines to a text file?

Time:12-11

Suppose we want to write a text file containing

user001
user002
user003
....
user999

Is there any smart way to build it instead of writing a program? Of course it would be easy by writing a C program or an awk script.

I am trying to find some automatic way in vi/vim or in a shell to add lines containing a constant text pattern and the updated value of a counter.

CodePudding user response:

There are a couple of interesting ways to do this in a short amount of characters

For bash:

echo user{000..999} | tr ' ' '\n' > file

or

seq 000 999 | sed 's/^/user/' > file

For vim:

You could just invoke one of the bash solutions using :r!

:r!seq 000 999 | sed 's/^/user/'

You could also just run seq from vim, and prepend "user" to all the lines

:r!seq 000 999
:%s/^/user

vim: animated gif of the above solution

or do it in a completely vim-native way:

  • generate a 1000 lines containing just "user000": i user000 CRESC999.
  • select all text: ggctrl-vG$
  • tell vim to increment them one by one: gctrl-a

vim: second animated gif of the above solution

CodePudding user response:

for counter in {001..999}; do echo "user${counter}" >> outputfile; done

For vim, there's a good answer here: https://vi.stackexchange.com/a/5600

CodePudding user response:

A bash one-liner, without using an explicit loop nor an external utility:

printf 'user%s\n' {001..999} >> outputfile

This uses printf's implicit loop and requires bash version 4.0 or newer (for leading zeros in brace expansions).

CodePudding user response:

You can use loops in shell. If you just paste this snippet into your terminal and press enter, it will create the file at your current location:

for i in {1..999}; do echo $(printf "userd" $i) >> test.txt; done

the loop iterates the variable i. Note that it's not enough to just concatenate "user" with i because we need leading 0s. Thus we need to format the number with d, meaning it is a decimal that contains at least 3 digits. A number smaller than 100 will be prefixed with 0s. With source >> target you can take the result from the echo command and write it into the file.

  • Related