简体   繁体   中英

Removing the following characters after a pattern in a text file in Unix

I have a text file which has the following lines:

Customer Details Report - A03_2014-01-04_09-00-09.txt
DemandResetFailureReport_2014-01-04_11-00-08.txt
ExcessiveMissingReadsReport_2014-01-04_09-00-11.txt
LipaBillingSumCheckReport_2014-01-04_11-00-08.txt
LipaUsageBillingReport_2014-01-04_12-55-06.txt

I want to run a command in UNIX (say, sed ) which will edit the contents of the text file as:

Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

I came across some commands such as sed '/^pattern/ d' to remove all lines after pattern. But where is the text file specified in the command?

With awk you can set - and _ as field separator ( -F[-_] ) and print the first block ( {print $1} ):

$ awk -F"[-_]" '{print $1}' file
Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport
grep -o '^[^-_]*' 

outputs:

Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

I always use perl -pi, as follows:

$ perl -pi -e 's/[-_].*//' file
$ cat file
Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

If a backup of the original is needed, specify a suffix for the backup file, for example:

$ perl -pi.bak -e 's/[-_].*//' file

See also the following topic on editing files in place: sed edit file in place

I would suggest using sed -i 's/[-_].*//' file.txt . Your text file ( file.txt ) must be passed as argument (I chose that way) or on standard input ( sed 's/[-_].*//' < file.txt > file2.txt ), but that way you could not edit it in-place ( -i ). Be sure not to use sed … <file.txt >file.txt as that will delete your file.txt contents .

这可能对您有用(GNU sed):

sed -ri 's/( -|_).*//' file

Another awk

awk '{sub(/[-_].*/,x)}1' file
Customer Details Report
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

This removes what you does not want and print the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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