Can you please help add multiple lines of txt to the file via bash script through vim?
I tried this:
vim -c "3 s/^/
add-this-line1
add-this-line2
add-this-line3/" -c "wq" /var/www/html/webserver/output_file.txt
But, the output of the file looks like this:
3 add-this-line1 add-this-line2 add-this-line3
What I want to do is, add the lines one by one FROM the line 3 in the output_file.txt
not at the line 3 one next to another.
CodePudding user response:
This is more of a job for ed, IMO
seq 10 > file
ed file <<END_ED
3a
first
second
third
.
wq
END_ED
cat file
1
2
3
first
second
third
4
5
6
7
8
9
10
CodePudding user response:
if you really want to do it via vim, I believe you need to insert new lines in your substitution:
vim -c "3 s/^/add-this-line1\radd-this-line2\radd-this-line3\r/" -c "wq" /var/www/html/webserver/output_file.txt
CodePudding user response:
With ex
or ed
if available/acceptable.
printf '%s\n' '3a' 'foo' 'bar' 'baz' 'more' . 'w output_file.txt' | ex -s input_file.txt
Replace ex
with ed
and it should be the same output.
Using a bash array to store the data that needs to be inserted.
to_be_inserted=(foo bar baz more)
printf '%s\n' '3a' "${to_be_inserted[@]}" . 'w output_file.txt' | ex -s inputfile.txt
Again change
ex
toed
should do the same.If the
input
file needs to be edited in-place then remove theoutput_file.txt
just leave thew
.
Though It seems you want to insert from the beginning of the line starting from line number "3 s/^/
Give the file.txt
that was created by running
printf '%s\n' {1..10} > file.txt
A bit of shell scripting would do the trick.
#!/usr/bin/env bash
start=3
to_be_inserted=(
foo
bar
baz
more
)
for i in "${to_be_inserted[@]}"; do
printf -v output '%ds/^/%s/' "$start" "$i"
ed_array =("$output")
((start ))
done
printf '%s\n' "${ed_array[@]}" ,p Q | ed -s file.txt
Output
1
2
foo3
bar4
baz5
more6
7
8
9
10
Change
Q
tow
if in-place editing is needed.Remove the
,p
if you don't want to see the output.