0

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?

Jotne
  • 40,548
  • 12
  • 51
  • 55
user3114665
  • 605
  • 1
  • 5
  • 6
  • BTW `sed '/^pattern/d'` removes all lines having the word `pattern` at the beginning. If you use a regex instead of `^pattern`, it removes all lines matching that pattern. – Palec Jan 06 '14 at 14:57

6 Answers6

2

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2
grep -o '^[^-_]*' 

outputs:

Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport
Kent
  • 189,393
  • 32
  • 233
  • 301
1

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

Community
  • 1
  • 1
Gerrit Brouwer
  • 732
  • 1
  • 6
  • 14
0

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.

Community
  • 1
  • 1
Palec
  • 12,743
  • 8
  • 69
  • 138
0

This might work for you (GNU sed):

sed -ri 's/( -|_).*//' file
potong
  • 55,640
  • 6
  • 51
  • 83
0

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.

Jotne
  • 40,548
  • 12
  • 51
  • 55