Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a string and the contents of a file in BASH?

I am trying to concatenate the contents (a block of code) of a file called query.sql in a README.md document, that already contains some text. However, I would also like this block of code to be preceded by a heading "Model answer".

In other words, if my README.md file was currently structured as

# Title

Some text here.

the new file should look like

# Title

Some text here.

## Model answer

```sql
Contents of query.sql
```

The subtitle ## Model answer is currently not in any file, so the process should involve something like

cat "## Model answer\n\n```sql\n" query.sql "\n```" >> README.md

but cat only works with sets of files, not files and strings. How could I achieve the desired result in BASH?

like image 473
SeSodesa Avatar asked Oct 28 '25 04:10

SeSodesa


1 Answers

First you can printf or echo -e the required text and then cat the file query.sql after that. You can use && or ; between the commands . If && is used then the second command will be executed only if the first command was successfull. ; is treated as a command separator

{ printf "## Model answer\n\n \`\`\`sql" && cat query.sql && printf "\n\`\`\`"; } >> README.md

or

{ echo -e "## Model answer\n\n '''" ; cat query.sql ; echo -e "''' /n"; } >> README.md
like image 95
j23 Avatar answered Oct 29 '25 17:10

j23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!