Friday 15 April 2011

bash - Replace a string in the last 100 records on a file using awk -



bash - Replace a string in the last 100 records on a file using awk -

so got around processing lastly 100 records of file declaring variable using wc -l i'm having hard time getting sub portion of awk want.

the text below illustration helps me point across table

gold 1 1986 usa american eagle gold 1 1908 austro-hungarian empire franz josef 100 korona silver 10 1981 usa ingot gold 1 1984 switzerland ingot gold 1 1979 rsa krugerrand gold 0.5 1981 rsa krugerrand gold 0.1 1986 prc panda silver 1 1986 usa liberty dollar gold 0.25 1986 usa liberty 5-dollar piece

let's phone call file coins , assume there's on 400 records

awk -v v1=$(wc -l < coins) 'nr > v1-100 {gsub /gold/magic/; print}' coins

it doesn't work me, it'll work if want print first field can't seem around specifying number of records , processing them. i'd know how go on replacing string , if needed, printing fields off of processed text after replacing string awk , print entire file including records have been replaced

give try:

awk -v v1="$(wc -l < coins)" 'nr>(v1-100){gsub(/gold/,"magic")}7' coins

this output 400 lines (say file has 400lines), substitution done on lastly 100 lines.

or line number reading file twice awk:

awk 'nr==fnr{num=nr;next}fnr>(num-100){gsub(/gold/,"magic")}7' coins coins edit

op wants lastly 100 lines in output:

awk 'nr==fnr{num=nr;next}fnr>(num-100){gsub(/gold/,"magic");print}' coins coins

or can utilize tail:

tail -100 coins|awk 'gsub(/gold/,"magic")+7'

bash awk gsub

No comments:

Post a Comment