简体   繁体   English

bash / sed / awk从文本文件中删除或gsub时间戳模式

[英]bash / sed / awk Remove or gsub timestamp pattern from text file

I have a text file like this: 我有一个这样的文本文件:

1/7/2017 12:53  DROP TABLE table1                                                   
1/7/2017 12:53  SELECT  

1/7/2017 12:55  --UPDATE #dat_recency SET
Select * from table 2
into table 3;

I'd like to remove all of the timestamp patterns ( M/D/YYYY HH:MM , M/DD/YYYY HH:MM , MM/D/YYYY HH:MM , MM/DD/YYYY HH:MM ). 我想删除所有时间戳模式( M/D/YYYY HH:MMM/DD/YYYY HH:MMMM/D/YYYY HH:MMMM/DD/YYYY HH:MM )。 I can find the patterns using grep but can't figure out how to use gsub . 我可以使用grep找到模式,但无法弄清楚如何使用gsub Any suggestions? 有什么建议么?

DESIRED OUTPUT: 期望的输出:

DROP TABLE table1                                                   
SELECT  

--UPDATE #dat_recency SET
Select * from table 2
into table 3;

You can use this sed command to remove data/time stamps from line start: 您可以使用以下sed命令从行开头删除数据/时间戳:

sed -i.bak -E 's~([0-9]{1,2}/){2}[0-9]{4} [0-9]{2}:[0-9]{2} *~~' file

cat file

DROP TABLE table1
SELECT

--UPDATE #dat_recency SET
Select * from table 2
into table 3;

Use the default space separator, make first and second columns to empty string and then print the whole line. 使用默认的空格分隔符,使第一和第二列为空字符串,然后打印整行。

awk '/^[0-9]/{$1=$2="";gsub(/^[ \t]+|[ \t]+$/, "")} !/^[0-9]/{print}' sample.csv

the command checks each line whether starts with numeric or not, if it is replace the first 2 columns with empty strings and remove leading spaces; 该命令检查每行是否以数字开头,如果是,则用空字符串替换前两列,并删除前导空格; otherwise print the original line. 否则,打印原始行。

output: 输出:

DROP TABLE table1
SELECT

--UPDATE #dat_recency SET
Select * from table 2
into table 3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM