Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion A strange issue when using awk to substitute a field in specific line.
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Geoff Clare  
View profile  
 More options Oct 11 2012, 8:41 am
Newsgroups: comp.unix.shell
From: Geoff Clare <ge...@clare.See-My-Signature.invalid>
Date: Thu, 11 Oct 2012 13:33:17 +0100
Local: Thurs, Oct 11 2012 8:33 am
Subject: Re: A strange issue when using awk to substitute a field in specific line.

Hongyi Zhao wrote:
> $ cat sub_test.awk
> baseDirForScriptSelf="$(cd "$(dirname "$0")"; pwd)"
> awk  -v a=$baseDirForScriptSelf  '{if($1=="set" && $2=="base_path") sub(/
> ^.*$/,a"/apt-mirror",$3);print}'  ./for_test 1<>./for_test

> But, after I run the sub_test.awk, I found that the for_test file become
> the following one:

> $ cat for_test
> set base_path /home/werner/Desktop/test_awk_sub/apt-mirror
> clean http://mirror.bjtu.edu.cn/debian
> clean http://mirror.bjtu.edu.cn/debian-multimedia
> ltimedia

> As you can see, the final for_test becomes four lines in it.  The last
> line "ltimedia" is appeared when I issue the command:

> $ ./sub_test.awk

> I cann't figure out why this should happen.  Could you please give me
> some hints on this strange thing?

Because you are using 1<>file to redirect standard output, the shell
does not truncate the file before executing awk.  When awk writes to
the file it is overwriting existing data.  Your transformation
shortens the data, and therefore there is some of the old data
left at the end when awk has finished writing the new data.

The 1<>file trick is neat, but it should only really be used when
you are doing a one-to-one transformation.  It's also only safe if
the transformation is idempotent (i.e. repeating the change does
not alter the result).  This is so that if awk is killed part way
through, you can just restart it from the beginning.

An example of a safe usage is:

$ cat for_test
abcabc
$ awk '{ gsub(/b/, "B"); print }' for_test 1<>for_test
$ cat for_test
aBcaBc

--
Geoff Clare <netn...@gclare.org.uk>


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.