LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   prepending text dynamically to a file (https://www.linuxquestions.org/questions/linux-newbie-8/prepending-text-dynamically-to-a-file-704344/)

curos 02-13-2009 01:13 AM

prepending text dynamically to a file
 
I have a command line program (not mine) that checks the first line of a file for a certain string. For example, lets say it looks for three x's. If it doesn't find those three x's, it exits. Now I want to run this program on some files but they all don't have the three x's at the top. Is there a way to dynamically prepend that text to the file before it is passed to the program?

I have a way currently, but it doesn't do it "on the fly". I have to make temporary files first and then feed it into the command line program.

Let's say the command line program is called `check`

$ ./check example_file
Error: could not find three x's at the top of file
$ echo "xxx" > header
$ cat header example_file > example_file_prepended
$ ./check example_file_prepended
Success: three x's found


So I was wondering if there was some way to dynamically prepend to the file, before the check command line program reads the file.

Does that make sense?

David the H. 02-13-2009 03:29 AM

There are probably a hundred different ways to do what you want. You could certainly do it with sed or awk, for example, though I don't know the syntax for them offhand. But a quick and dirty way I've used is something like this:

Code:

echo -e "xxx\n$(cat example_file.txt)" > example_file.txt
Edit: here's a solution using sed:
Code:

sed -i 1i\ xxx example_file.txt
The -i flag in sed makes it modify the original file in place, 1i\ means insert text at line one, and is followed by the text you want to insert.


All times are GMT -5. The time now is 09:32 PM.