2014-08-31 59 views
0

我目前正在读取unix中三个字母字符串的文件,并想知道如何去制作行变量,以便我可以在代码中grep它们...指定一行变量名称Unix

我的想法是这样的:

!#/bin/bash 

IFS='' 
while read line 
    do 
    code=$(line) 
    #This would be where I want to assign the line a variable 
    grep "$code" final.txt > deptandcourse.txt 
    #This is where I would want to grep according to that three letter string 
done < strings.txt 

示例文件(strings.txt):

ABC 
BCA 
BDC 

我希望把这些信件在变线,然后用grep的文件(final.txt )首先为'ABC',然后是'BCA',然后是'BDC'

+1

'line'是一个变量了。你究竟是什么意思? – 2014-08-31 04:53:37

+0

提供示例文本,以及如何输出。 – Jotne 2014-08-31 05:13:44

回答

0

line是一个变量,您设置为包含您在整个循环中读取的每一行文件的内容,因此您不需要将其重新分配给另一个变量。有关在循环中使用read的更多信息,请参阅this page

此外,它看起来像你可能想要附加到deptandcourse.txt>>因为使用>重定向将每次覆盖文件。

也许这是你想要什么:

while read -r line 
    do 
    grep "$line" final.txt >> deptandcourse.txt 
done < strings.txt 

由于@JohnZwinck在他的评论中建议:

grep -f strings.txt final.txt > deptandcourse.txt 

这似乎是最好的解决办法。

你也可以使用awk来完成同样的事情:

awk 'FNR==NR { 
    a[$0] 
    next 
} 
{ 
    for(i in a) 
     if($0 ~ i) 
      print 
}' strings.txt final.txt > deptandcourse.txt 
+0

谢谢!这是我想要做的! – user3875711 2014-08-31 05:17:32

+0

不客气,很高兴提供帮助。 – 2014-08-31 05:46:09

+2

@ user3875711:它有点像你真正想要的是这样一行:'grep -f strings.txt final.txt'。没有? – 2014-08-31 06:45:56