【问题标题】:Extract data from one text file从一个文本文件中提取数据
【发布时间】:2013-10-15 05:51:50
【问题描述】:

抱歉造成混乱,我需要一个脚本,我的要求是如果我是 具有包含标题、记录和尾部的文本文件 例如:- 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 会是这样的
测试2.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

【问题讨论】:

标签: shell unix


【解决方案1】:

假设您的脚本文件名为 special_copy.sh,并且您向其传递了 3 个参数,按照您的示例命名为 test1.txt、test2.txt 和 test3.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的文件。

【讨论】:

  • 但是我每次都需要运行脚本,有没有其他方法应该从一个脚本运行整个过程
  • 我在这里很困惑。创建这两个文件只需要两个步骤,我已经让您创建一个 shell 脚本文件并使用这个文件。如果这不是您想要的,请发布完整的问题。
【解决方案2】:
#!/bin/bash
tail -n +2 test1.txt | head -n -1 > test2.txt
cp test1.txt test2.txt
exit 0

【讨论】:

  • 在任何脚本中写上上面的代码,比如 并运行它:sh DataExtract
猜你喜欢
  • 1970-01-01
  • 2020-12-20
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多