从一个文本文件中提取数据

时间:2013-10-15 05:51:51

标签: shell unix

抱歉造成混乱,我需要一个脚本,我的要求就是我 有文本文件,其中包含标题,记录和尾巴 例如: - Test1.txt(输入文件)
例如
我有一个文本文件

输入文件

test1.txt   
---------   
2013101000490398938---HEADER
rohitroshankavuriM26single2010198702092013000(4053 characters each line contains)
rohitroshankavuriM26single2010198702092013000(4053 characters each line contains)
rohitroshankavuriM26single2010198702092013000(4053 characters each line contains)
rohitroshankavuriM26single2010198702092013000(4053 characters each line contains)
rohitroshankavuriM26single2010198702092013000(4053 characters each line contains)
201310100004005--TAIL

我需要编写一个UNIX shell脚本,它将从中提取特定的列数据 输入文件根据他们的位置,因为我没有分隔符或甚至没有分隔符 在这里,我必须提取一些列(随机我可以根据他们的选择 位置)并将它们保存到文本文件

假设例如:如果我需要一个应该从位置提取数据的文本文件 1-5,6-8,9,10-12如图所示,它不应包含标题和尾部。

normally i have used this script to

#Create as same as the input file    
cat Test1.txt>tmp.txt    
#here i will delete the header and tail from the tmp.txt file    
sed '1d,$d' tmp.txt    
#now i will extract the data based upon the    
cut 1-5,6-8,9,10-12 Test1.txt>Test2.txt  

O / P将是这样的     的test2.txt
    ---------
    rohitroshank
    rohitroshank
    rohitroshank
    rohitroshank

现在我的第一个输出文件已准备好Test2.txt

我的第二个要求

现在与第一个输出文件相同的输出但是在这里我可以选择一些不同的列但是它 应该包含带有标题,记录,尾部的数据 例如:

要打印标题的第一行,之后我有记录和之后 尾巴

Test3.txt(output file)      
--------------------------    
 #to print the head    
 head -1 tmp.txt>Test3.txt     
 #now i will pick specific columns based upon my positions & append it to test3.txt
 cut 13-15,16-19,20 tmp.txt>>Test3.txt    
 #print and append it to Test3.txt file     
 tail -1 tmp.txt>>Test.txt 

输出Test3.txt

2013101000490398938
avuriM26
avuriM26
avuriM26
avuriM26
avuriM26
avuriM26
avuriM26
201310100004005

直到现在我的要求已经完成但是有没有其他简单的方法可以解决这个问题     输出。如果是,请分享我的脚本,这样对我有用。

And but also now i am stuck with a problem i.e     
extracting specific columns data using CUT command.see any text file      
each line will contain 1024 characters but i have 4093 characters so how would i 
approach this requirement rather than doing it using CUT.

Is there any other way please suggest me. If are having any queries regarding my
requirement comment it here

2 个答案:

答案 0 :(得分:0)

假设您的脚本文件名为special_copy.sh,并根据您的示例将3个参数传递给它,名为test1.txttest2.txttest3.txt,请将以下内容粘贴到sh文件:

head -n -1 $1 | tail -n +2 > $2
cp $1 $3

然后将其称为sh special_copy.sh test1.txt test2.txt test3.txt

基本上,它会从test1.txt读取,将除第一行和最后一行以外的所有行复制到test2.txt,然后只需复制名为test3.txt的文件。

答案 1 :(得分:0)

#!/bin/bash
tail -n +2 test1.txt | head -n -1 > test2.txt
cp test1.txt test2.txt
exit 0