Add multiple lines at the beginning of the file
I have many files in the same subdirectory that looks like this:
10 A
11 T
12 A
13 C
15 A
i.e. two columns, where the first row always starts with 10.
I would just like to add lines 1-9 to the beginning of each ie file
1
2
3
4
5
6
7
8
9
10 A
11 T
12 A
13 C
15 A
I don't need to add a second column.
I know what I could do
sed -i '1i1' FILE
to add the first line, but do I need to enter this command for every additional line I want to add?
source to share
You can use Unix / POSIX / Linux utility cat
to concatenate and print files.
You can use it <(seq 5)
as a replacement file to create an initial sequence. So you can do:
$ cat <(seq 5) file
1
2
3
4
5
10 A
11 T
12 A
13 C
15 A
Then, if you want the edit effect to be set, you can do:
$ cat <(seq 5) file > tmp && mv tmp file
Then:
$ cat file
1
2
3
4
5
10 A
11 T
12 A
13 C
15 A
If you haven't seq
, you can do:
$ cat <(echo {1..5} | tr ' ' '\n') file
instead of this. (Using 5 lines versus 9 in your example. Obviously how to change that ...)
If you have many files or want to create a second column, you can create a header row:
$ header=$(for ((x=1; x<=5; x++)); do printf "%s #\n" $x; done)
$ echo "$header"
1 #
2 #
3 #
4 #
5 #
Then you can use this line instead of running seq
or something:
$ cat <(echo "$header") file
1 #
2 #
3 #
4 #
5 #
10 A
11 T
12 A
13 C
15 A
source to share
Alternatively, you might want a pure bash:
$ cat file4
10 A
11 T
12 A
13 C
15 A
$ printf '%s\n%s\n' {1..9} "$(<file4)"
1
2
3
4
5
6
7
8
9
10 A
11 T
12 A
13 C
15 A
To replace the original content of a file, you can do it like this:
printf '%s\n%s\n' {1..9} "$(<file4)" >file44 && mv -f file44 file4
Also sed -i
this is what it does in the background (check sed manpages)
For multiple files, you can use a loop:
for f in *;do printf '%s\n%s\n' {1..9} $(<"$f") >tmp"$f" && mv tmp"$f" "$f";done
source to share