2012-06-01 57 views
-1

我习惯vi而不是vim。对于我的工作,我正在尝试使用ksh和vi来创建脚本。我想要做的是能够打开并搜索文件中的关键术语并提取信息。例如,我想运行一个ksh脚本,该脚本搜索文件中的关键术语“主题”,然后提取“第一行”信息。我想使用vi的原因是因为我然后想写一个文件来将我提取的值写入由逗号分隔的一行中。Ksh和Vi脚本

Subject: line one 
Content: line two 

谢谢任何​​帮助和参考。

编辑:是的,使用sed,awk和grep是更有效的方法。但我有分配我的结果在ksh的一个变量的一个问题,目前我有:

testing=grep Primary /u/mtjandr/temp.txt | sed -e 's/[:a-zA-Z]* //g' 
grep Primary /u/mtjandr/temp.txt | sed -e 's/[:a-zA-Z]* //g' 

它本身。OUPUTS正确的结果,但是当我尝试将其分配给一个变量,我得到erorr

copy_group.sh [18]:主要:未找到。

更新:我发现我的解决方案:

testing=`grep Primary /u/mtjandr/temp.txt | sed -e 's/[:a-zA-Z]* //g'` 
+3

我还是不明白,为什么你必须使用'六。还有许多其他更简单的方法来实现使用工具,专门为此目的而设计的,例如'sed','awk','grep'。 –

+1

......另外,为了提高您获得合理答案的机会,您可能还需要包括一个*期望输出的例子*和[您已经尝试过](http://whathaveyoutried.com)的描述。 –

回答

1

鉴于您的文件可能看起来普通,你会想看看awkgrepsed肖恩提及。 Grep给你你感兴趣的行,awk提取字段和sed编辑整个事情。

因此,在你的榜样,你会希望找到包含Subject行:

grep Subject file 

,并提取line one

awk '{printf "%s %s,", $2, $3}' 

终于卸下插在文件的结尾额外,

sed 's/,$//' 

这三个命令需要将管道连接到一起:

grep Subject file | awk '{printf "%s %s,", $2, $3}' | sed -e 's/,$//' 

当然,awk部分需要进行定制,以您的确切文件结构。

最后,写在另一个文件(而不是输出)整个事情,你可以在命令的输出重定向上面的文件:

grep Subject file | awk '{printf "%s %s,", $2, $3}' | sed -e 's/,$//' > other_file 
0

正如我上面的评论说,有很多实现使用工具的其他更简单的方法就是为了这个目的而设计的,例如sed,awkgrep

如果你决定给其他的东西比vi一展身手,那么这里就是使用单一awk命令版本:

awk '/^Subject: /{printf "%s%s",x,substr($0,10);x=","}' in.txt > out.txt 

例子:

[[email protected]]$ cat in.txt 
Subject: line one 
Content: line two 
Subject: line three 
yadda yadda 

[[email protected]]$ awk '/^Subject: /{printf "%s%s",x,substr($0,10);x=","}' in.txt > out.txt 
[[email protected]]$ cat out.txt 
line one,line three 

x=','位,所以我们可以用逗号前面的所有输出与第一个输出区分开来。对于更易读的内容,我们可以简单地将输出记录分隔符(ORS)从\n更改为逗号。这个用户将导致一个尾随的逗号,我们需要用另一个命令删除它。

在这个例子中,我们管道输出到sed删除尾随分隔符:

awk -v ORS=',' '/^Subject: /{print substr($0,10)}' in.txt | sed -e 's/,$//' > out.txt 

命令的故障:

awk -v ORS=',' '/^Subject: /{print substr($0,10)}' in.txt | sed -e 's/,$//' > out.txt 
    _________ __________ ___________________ ______ _______________ _________ 
     |    |    |    |    |   | 
separate output  |   OUtput the line  |  Remove trailing | 
records with  |   from char 10   |   comma   | 
comma (not \n)  |    onwards   |       | 
        |        |     Redirect output 
      Match lines that     input file    to out.txt 
      start with "Subject :"