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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting line in a file 2

Status
Not open for further replies.
Aug 3, 2001
29
US
I have a file where I am reading through directories then files. I read each line and find a match = THR
I want to insert a line before only this in the file.

I have tried different perl commands -i but only get blank lines to appear.

thanks, for any assistance


Len Turnbull
 
awk '/THR/ {print "Your line"} {print $0}' $FILE > $FILE.new
 
Could you explain the $0 variable ???
also are the {'s to be used or are these for editting purposes ??


Thanks,

len
 
The matched pairs of {} are vital to awk,gawk and nawk
$0 is the entire record parsed in by awk.
Individual fields within a record are referred to by postion eg $1 is the first, $(NF) is last.
man awk will give an overview. Dickie Bird (:)-)))
 
I use sed for this:

sed '/THR/{x;s/^/line_to_insert/;G;}' your_file > new_file

-jim
 
$0 means the whole line and is (confusingly) optional in this instance. The {'s are to be used as they are part of the awk syntax. You should be able to just copy and paste with no problems. e.g.
[tt]
$ cat file1
purple
THR
star
$ TEXT="Your text goes here"
$ awk -v TEXT="$TEXT" '/THR/ {print TEXT} {print}' file1
purple
Your text goes here
THR
star
[/tt]
Try "man awk" for more details.
 
Here is the results of sed command on file
$ echo $var4
lendennissri
$ sed '/THR/{x;s/^/$var4/;G;}' $file > $file.new
FNR 0 0 20030227081712 out
$var4
THR 0 0 ST M

is there any other syntax I am not using ???

thanks for the help


Len

 
Use single quotes around $var4
sed '/THR/{x;s/^/'$var4'/;G;}' $file > $file.new
Dickie Bird (:)-)))
 
Ygor,
Your awk command worked perfectly....

I really appreciate the response and assistance


Len
 
The sed command needs double quotes around it when performing variable substitution:

sed "/THR/{x;s/^/$var4/;G;}" $file > $file.new

-jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top