如何使用schell脚本从文件读取元素,做一些计算和回写?

我只是脚本语言的新手。

现在我有一个文件,里面是:

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

我只想使用shell脚本(bash)按元素读取文件元素。 然后,我想对元素A1,A2和A3进行一些计算,然后将它们写回新文件(或旧文件)。 所以新文件会是(假devise算结果是D1,D2和D3):

  D1 B1 C1 D2 B2 C2 D3 B3 C3 

计算是通过命令“date -d @(A's value)”将Unix历元时间(A的值)转换为人类可读的时间(D的值)。

我尝试使用awk命令:

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

但它似乎有一些语法错误:>错误是:

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

你的要求是如此不清楚 ! 你是什​​么意思?

我可以给你一个例子,希望它有助于:

 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 

编辑

在这里我可以给你一个例子如何在awk中调用date

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

我想这就是你要找的。

祝你好运。

如果您需要使用UNIX日期而不是gawks内置时间函数,那么只需在shell中执行以下操作:

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

尽可能使用gawk。