bashechocat

How to cat text string and file in bash in way to preserve literal \newpage in output?


I have multiple markdown files that I am trying to concatenate into one markdown file in bash. I can concatenate markdown files and preserve “\newpage” lines, but when trying to add a group title via a string calling echo to each group it wont preserve literal \newpage in file. I am bash beginner and learning as I go. How can I achieve this without making a file just storing group name with \newpage?

Examples of a single item in single markdown file

## Item 1 of group 1

Text to item 1 of group 1.

\newpage
## Item 2 of group 1

Text to item 2 of group 1.

\newpage
## Item 1 of group 2

Text to item 1 of group 2.

\newpage

Desired output after grouping all items under one group and adding a group title “Title of group 1” with \newpage at the end

# Title of group 1

\newpage

## Item 1 of group 1

Text to item 1 of group 1.

\newpage

## Item 2 of group 1

Text to item 2 of group 1.

\newpage

# Title of group 2

\newpage

## Item 1 of group 2

Text to item 2 of group 2.

\newpage

I can group items into each groups markdown file by using following code (this part works and \newpage is preserved:

dir_in="/path/do/input_directory/"
dir_out="/path/do/output_directory/"
file="group_1"
for f in ${dir_in}${file}/*.md; do cat $f >> ${dir_out}${file}.md; echo >> ${dir_out}${file}.md; done

How should I edit the code above so I could add a group name “# Title of group 1 \newpage” from string variable?


I tried making a title into a variable and echo with content of grouped markdown file.

title="#Title of group 1 \newpage"
content=$(cat "${dir_out}${file}.md")
result=$(echo "${title}\n\n${content}")
echo "$result" > ${dir_out}${file}.md

But echo interprets every \n and prints newlines out and leaves “ewpages" into file.

#Title of group 1

ewpage

Solution

  • $ title='#Title of group 1 \newpage'
    $ printf '%s\n' "$title"
    #Title of group 1 \newpage
    $
    

    See why-is-printf-better-than-echo to learn about the problems with echo, see https://mywiki.wooledge.org/Quotes to learn when to use single vs double vs no quotes and always run your code through http://shellcheck.net until you get more familiar with shell programming.