Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting into multiple files

Status
Not open for further replies.

Rustican

Programmer
Aug 3, 2004
4
US
How can i use awk to insert the first line of multiple files in a directory?

Example: Inserting a name into txt files.

Jon Doe
Rest of file...



 
Insert the same line into all files in a directory?
Code:
for f in $(ls)
do
  mv $f ${f}.tmp
  echo 'John Doe'|cat - ${f}.tmp>$f
done


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
this will not leave cadaver in your dir
Code:
#!/bin/sh

# not assuming [k|ba]sh is used
for file in `ls` 
do [ -w $file ] || continue
   (
    echo blabla blabla
    cat $file
    ) >temp.file
    mv temp.file $file
done
note: a sed or an here-vi are eleganter.
 
It is possible to do this in awk, but involves loading the entire contents of each file into an array.
Code:
BEGIN{a[0]="john doe"}
f!=FILENAME&&c{p();c=0}
{a[++c]=$0;f=FILENAME}
function p(){for(x=0;x<=c;x++) print a[x] > f;close f}
END{p()}
Example usage...
[tt]
awk95.exe -f awkprog *.txt[/tt]
 
Thanks for all the help. I'll give them a try.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top