Creating a new file that has one line added to to the first line and one line added to the last

1

I need help or I will do this is python instead (by reading one line at a time) which I know I should not need to.

I have large number of text files that I get using find.

FILES=$(find ... -iname "*.txt")
num=0
for doc in $FILES; do
     echo "start string" > cat $doc > echo "end string" > "outfile$num.txt"
     let num=num+1
done

I dont know to many unix commands, but what I want to do is something like this:

output "start string" then cat $doc then "end string" to stdout and store in the outfile.

Thank you for your help!!

Erik

Posted 2012-09-12T04:56:56.327

Reputation: 137

Answers

0

use

{echo "start string"; cat $doc; echo "end string"} > "outfile$num.txt"

Or alternatively:

echo "start string" > "outfile$num.txt"
cat $doc >> "outfile$num.txt"
echo "end string" >> "outfile$num.txt"

Or yet another example using sed (you can do something similar with awk):

sed -e '1i start string;$a end string' $doc > "outfile$num.txt"

In the first example the three commands are simply executed sequentially and the output is then fed as a whole to the output redirect > "outfile$num.txt".

In the second example we do it in three commands and use the >> operator instead of the > operator to concatenate the output to the given file instead of replace the given file with the output.

Also, as an aside, you should be careful with your use of for doc in $FILES, this splits on spaces, so if any of your filenames contain spaces they will be interpreted as multiple file names instead of one file name.

wich

Posted 2012-09-12T04:56:56.327

Reputation: 140

Thank you, regrettably I have too much work to do (and too little time) to read up on Unix and different utility programs.

Even though my question was probably a dumb question, stress really makes you not think clearly. You have made my day much better, thanks again! :) – Erik – 2012-09-12T05:22:47.540

The first example needs a little tweaking: { echo ...; cat $doc; echo ...; }. Spaces to separate the braces from the contents, and a required semicolon after the last echo. – chepner – 2012-09-12T15:54:43.723