Reputation: 932
I have a text file (FILE_A.txt) with this content:
Content1
Content2
Content3
And other text file (FILE_B.txt) with this content:
A[#]
B[#]
C[#]
I would like to combine FILE_A.txt and FILE_B.txt in other file (FILE_C.txt) in this way:
A[Content1]
B[Content2]
C[Content3]
How could I make this using bash shell in linux (sed, cut, grep, etc)?
Upvotes: 2
Views: 2671
Reputation: 86844
The following reads both files concurrently, one line at a time, and store the lines in $value
and $template
. We then use bash's variable substring replacement to replace #
within $template
with the contents of $value
.
exec 6<"FILE_B.txt" # open file for reading and assign file descriptor 6
while read -r value; do # loop through FILE_A.txt, storing each line as $value
read -r template <&6 # read a line from FILE_B.txt, store as $template
echo ${template/\#/$value} # replace value into the template in place of `#`
done <"FILE_A.txt"
exec 6<&- # close input file descriptor 6
Upvotes: 2
Reputation: 46826
Here we go.
# awk 'NR==FNR{a[NR]=$0;next;} sub(/#/,a[FNR])' FILE_A.txt FILE_B.txt
A[Content1]
B[Content2]
C[Content3]
How does this work?
NR==FNR
- causes the following statements to be run if the record number matches the FILE record number - that is, we are currently reading only the firs tfile.{a[NR]=$0;next;}
- Store values from the first file in an array.sub(/#/,a[FNR])
- Once we're in the second file, substitute #
for the matching value stored from the first file. Note that this isn't inside curly brackets, so it's being evaluated as a condition. If the sub()
statement succeeds, the current line is printed.Upvotes: 3
Reputation: 274532
Use paste
and sed
as follows:
$ paste File_B.txt File_A.txt | sed 's/#]\s*\(.*$\)/\1]/g'
A[Content1]
B[Content2]
C[Content3]
Upvotes: 2