如何使用谢尔脚本从文件中读取的元素,做了一些计算和回写? [英] how to use schell script to read element from a file, do some calculation and write back?

查看:264
本文介绍了如何使用谢尔脚本从文件中读取的元素,做了一些计算和回写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是新来的的脚本语言。

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

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

我只想用shell脚本(bash)的读取由元素文件元素。然后,我想做的元素A1,A2和A3的一些计算,然后将它们写回一个新的文件(或旧文件)。因此新的文件将被(假设计算结果是D1,D2和D3):

  B1 D1 C1
 D2 B2 C2
 D3 C3 B3

的计算是对Unix纪元时间(A值)转换为人类可读的时间(D的值)使用命令日期-d @(A值)。

我尝试使用awk命令:

 的awk'{$ 1 =`日期-d @ $ 1`}'的test.txt

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

  AWK:{$ 1 =`日期-d @ $ 3`}
AWK:防爆$ P $ ^ pssion字符无效'`'


解决方案

您的要求是这样的不清楚!你的意思如何计算?

我可以告诉你一个例​​子,希望它可以帮助:

 肯特$猫的test.txt
100 B1 C1
200 B2 C2
300 B3 C3#在该实施例中,计算是越来越A1的squre
肯特$ AWK'{$ 1 * = $ 1} 1的test.txt
10000 B1 C1
40000 B2 C2
90000 B3 C3#如果你想要得到的结果在newfile.txt,这样做:肯特$ AWK'{$ 1 * = $ 1} 1的test.txt> newfile.txt#然后肯特$猫newfile.txt
10000 B1 C1
40000 B2 C2
90000 B3 C3

修改

在这里我可以给你一个例子,如何调用日期在awk的:

 肯特$回声1359579362 B1 C1| awk的'{日期-d @$ 1 | $函数getline 1} 1'
周三1月30日21时56分02秒CET 2013 B1 C1

我想这是你在找什么。

好运。

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

解决方案

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.

这篇关于如何使用谢尔脚本从文件中读取的元素,做了一些计算和回写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆