using AWK
Polytropon
freebsd at edvax.de
Mon Dec 17 16:23:19 UTC 2012
On Mon, 17 Dec 2012 08:16:26 -0800, Devin Teske wrote:
>
> On Dec 17, 2012, at 3:39 AM, Jack Mc Lauren wrote:
>
> > Hi guys
> >
> > How can I read a file which contains a number and assign that number to a variable via awk programming? By the way, I want to use this awk program in a shell script.
> >
> > Thanks in advance
>
> Try this:
>
> awk -v file=/etc/ttys 'BEGIN { getline line <file; printf "First line from %s: %s\n", file, line }'
Or more verbose:
#!/bin/sh
filename=$1
echo "file is ${filename} with content:"
cat ${filename}
echo "calling awk..."
awk "BEGIN {
getline no < \"${filename}\"
close \"${filename}\"
print no
print no * 2
}"
# EXAMPLE:
# --------
#
# % ./awkvar.sh /tmp/no.txt
# file is /tmp/no.txt with content:
# 12345
# calling awk...
# 12345
# 24690
The example shows how to use the variable inside awk. You
could get rid of the getline function in case the file
contains only the number you're interested in. If you need
further processing of the file, you can do that inside
awk (e. g. omitting comment lines, obtain data from a given
line number of specific pattern).
--
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
More information about the freebsd-questions
mailing list