I'm trying to write a bash script, which will do the following:
For example:
first_file.txt:
111111
1111
11
1
second_file.txt:
122221
2222
22
2
pattern:
2222
output:
122221
111111
1111
11
1
2222
111111
1111
11
1
22
2
What should I use to realize this functionality on BASH?
I wrote the code, but it doesn't work properly (why?):
#!/bin/bash
first_filename="$1"
second_filename="$2"
pattern="$3"
while read -r line
do
if [[ $line=˜$pattern ]]; then
while read -r line2
do
echo $line2
done < $second_filename
fi
echo $line
done < $first_filename
You can use cat with redirection to append a file to another file. You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.
sed
can do that without loops. Use its r
command:
sed -e '/pattern/rFILE1' FILE2
Test session:
$ cd -- "$(mktemp -d)"
$ printf '%s\n' 'nuts' 'bolts' > first_file.txt
$ printf '%s\n' 'foo' 'bar' 'baz' > second_file.txt
$ sed -e '/bar/r./first_file.txt' second_file.txt
foo
bar
nuts
bolts
baz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With