Skip to content
Advertisement

Bash / ZSH – How to copy from a specific line to the end of a file, then paste at line 1 of another file whist preserving all text in that file

I am trying to add a bash script to my Azure Devops pipeline that automatically compiles a changelog.

When a PR is made, there will be a file committed call pr-changelog.md. I want all text from this file to be copied from a specific line onwards, say line 6. then I want this pasted in to another file called changelog.md at line 1, moving all text in that file down and preserving it. Both of these files will be at the root of my folder.

So far I have seen commands like cp, sed and awk suggested, but I am not sure how to target these specific files and paste in the last step to always preserve what’s already there.

What should my bash script be using to achieve this?

Advertisement

Answer

I would use the following :

cat <(tail -n+7 pr-changelog.md) changelog.md > output
mv output changelog.md

tail returns the end of the pr-changelog.md file, starting with line 7 when using -n+7.
<(...) is process substitution and will return the output stream of the command, which can be read by cat.
We concatenate that to the current changelog.md file to obtain the new one.

Careful not to try and do it in one operation : the > changelog.md would overwrite the content of changelog.md before it is read by cat.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement