Suppose I've got a text file that consists of two parts separated by a delimiting string ---
:
aa
bbb
---
cccc
dd
I am writing a Bash script to read the file and assign the first part to var part1
and the second part to var part2
:
part1= ... # should be aa\nbbb
part2= ... # should be cccc\ndd
How would you suggest write this in Bash?
You can use awk
:
foo="$(awk 'NR==1' RS='---\n' ORS='' file.txt)"
bar="$(awk 'NR==2' RS='---\n' ORS='' file.txt)"
This would read the file twice, but handling text files in the shell, i.e. storing their content in variables should generally be limited to small files. Given that your file is small, this shouldn't be a problem.
Note: Depending on your actual task, you may be able to just use awk
for the whole thing. Then you don't need to store the content in shell variables, and read the file twice.