From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 6273 invoked by alias); 18 May 2012 14:01:32 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 17095 Received: (qmail 16309 invoked from network); 18 May 2012 14:01:30 -0000 X-Spam-Checker-Version: SpamAssassin 3.3.2 (2011-06-06) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-2.6 required=5.0 tests=BAYES_00,RCVD_IN_DNSWL_LOW, SPF_HELO_PASS autolearn=ham version=3.3.2 Received-SPF: none (ns1.primenet.com.au: domain at csr.com does not designate permitted sender hosts) Date: Fri, 18 May 2012 14:30:25 +0100 From: Peter Stephenson To: Subject: Re: Extracting the 4th word of the first line in a file - is there a more elegant solution? Message-ID: <20120518143025.7d525f91@pwslap01u.europe.root.pri> In-Reply-To: <1337347014.26363.140661077285713.26DAE636@webmail.messagingengine.com> References: <1337347014.26363.140661077285713.26DAE636@webmail.messagingengine.com> Organization: Cambridge Silicon Radio X-Mailer: Claws Mail 3.7.9 (GTK+ 2.22.0; i386-redhat-linux-gnu) MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Originating-IP: [10.101.10.18] X-Scanned-By: MailControl 7.7.0.1 (www.mailcontrol.com) on 10.71.0.124 On Fri, 18 May 2012 15:16:54 +0200 Ronald Fischer wrote: > # $1 is the filename > line=$(head -n 1 $1) > field=${lin[(w)4]} It depends a bit how big the file is. If it's small, it's very easy, and involves no extra processes (the "$(<...)" is optimised to a read): field=${$(<$1)[4]} The disadvantage is that reads the entire file into memory first. It's hard to think of a way that avoids that that doesn't use an auxiliary process, but apart from that it's still relatively straightforward within zsh: field=${$(read -e <$1)[4]} This reads a single line from the file and echoes it instead of assigning it to a parameter. You might want "read -qe" if the file contains backslashes. You can do it without an auxiliary process, but with a local variable, which is probably more efficient and the best compromise: read -A line <$1 field=$line[4] -- Peter Stephenson Software Engineer Tel: +44 (0)1223 692070 Cambridge Silicon Radio Limited Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, UK Member of the CSR plc group of companies. CSR plc registered in England and Wales, registered number 4187346, registered office Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, United Kingdom More information can be found at www.csr.com. Follow CSR on Twitter at http://twitter.com/CSR_PLC and read our blog at www.csr.com/blog