how to use schell script to read element from a fi

2019-06-09 06:04发布

问题:

I am just new to the script language.

Now I have a file, inside it are:

>   A1 B1 C1
>   A2 B2 C2
>   A3 B3 C3

I just want to use the shell script(bash) to read the file element by element. Then I want to do some calculation of the element A1, A2 and A3 and then write them back to a new file(or the old file). So the new file would be (supposed the calculation results are D1,D2 and D3):

 D1 B1 C1
 D2 B2 C2
 D3 B3 C3

The calculation is to convert the Unix epoch time(A's value) into human readable time(D's value) by command "date -d @(A's value)".

I try to use the awk command:

awk '{$1=`date -d @$1`}' test.txt

But it seems to have some syntax error:> The error is :

awk: {$1=`date -d @$3`}
awk:     ^ invalid char '`' in expression

回答1:

your requirement is so unclear! what calculation did you mean?

I could show you an example, hope it helps:

kent$  cat test.txt
100 B1 C1
200 B2 C2
300 B3 C3

# in this example, the "calculation" is getting the squre of A1
kent$  awk '{$1*=$1}1' test.txt
10000 B1 C1
40000 B2 C2
90000 B3 C3

#If you want to get the result in a newfile.txt, do this:

kent$  awk '{$1*=$1}1' test.txt >newfile.txt

#then

kent$  cat newfile.txt 
10000 B1 C1
40000 B2 C2
90000 B3 C3

Edit

here I could give you an example how to invoke date in awk:

kent$  echo "1359579362 B1 C1"|awk '{"date -d @"$1|getline $1}1'                                                                                                            
Wed Jan 30 21:56:02 CET 2013 B1 C1

I guess that is what you are looking for.

good luck.



回答2:

If you need to use UNIX date on this instead of gawks builtin time functions, then just do it all in shell:

while read -r secs rest
do
   echo "$(date -d @"$secs") $rest"
done < test.txt

Use gawk if possible though.