Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add line at top and bottom of file before sending it to pipe

Tags:

linux

bash

I have a text file, say, text.

What I want to do is to put the text file into pipe (as in cat text |), but with added line at top and bottom - but without creating a new file (because the text file is kind of big) or modifying it.

Is that possible? I was thinking echo $(echo "line"; cat text; echo "line") but I don't like that.

like image 327
Karel Bílek Avatar asked Nov 30 '25 14:11

Karel Bílek


2 Answers

From man bash:

(list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list.

So this should work:

(echo first line; cat file; echo last line) | some_command

As suggested by chepner, when you don't need a subshell you can use {} instead of (). In this case, the ; is mandatory including for the last command in the group.

In the comments Pyrolistical remembers this also works if you have an incoming pipe instead of a file:

some_program | (echo first line; cat -; echo last line) | some-other-command

As in many unix command line applications, if the filename argument for cat is - it means "read from standard input".

like image 151
Paulo Scardine Avatar answered Dec 03 '25 10:12

Paulo Scardine


Copied from this question Add new lines to top and bottom of every text file:

cat text |sed -e '1 i beginning_line'| sed -e '$s@$@\nending_line@' |

it seems to work.

like image 38
Karel Bílek Avatar answered Dec 03 '25 09:12

Karel Bílek



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!