how to use awk to add information to a text file

Communications | Debian Support


awk '{if(/texttofind/) {printf("%s\nfromuser=%s\n",$0,substr($3,index($3,"<")+1,index($3,">")-2))} else print $0}' "file1.txt" > "file2.txt"

where:
if(/texttofind/) does A) if it is true or does B) if not true

texttofind is the text you want to add a new line after

printf("%s\nfromuser=%s\n",$0,substr($3,index($3,"<")+1,index($3,">")-2)

this statement prints the origional line in string format, then drops a new line with the /n. Then prints: fromuser=.. then prints a substring from the above line where the start of the substring is a "<" and the end of the substring is a ">"

"file1.txt" is the input file
"file2.txt" is the output file

Why would you need to do this? I had the problem where a huge configuration file needed me to add a line at the end of about 500 sections of code. Each added line of each section had to reference a unique value in the line above it. Do i sit there for 6 hours copying and pasting or do I run one command and get the computer to do it for me. I'll choose the one command...