21

Is there any cut command to cut based on a word eg :

171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD. The task has terminated abnormally because of a program check. 16:08:27

I want the output as :

171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD.

How to approach?

muru
  • 207,228
Anony
  • 803

5 Answers5

29

I suggest:

awk -F 'ABCD' '{print $1 FS "."}' file

Output:

171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD.

FS contains your delimiter "ABCD". "ABCD" is a regex.

Cyrus
  • 5,789
7

sed version:

sed 's/ABCD.*/ABCD./' input.txt
171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD.

Source: https://unix.stackexchange.com/questions/257514/how-to-delete-everything-after-a-certain-pattern-or-a-string-in-a-file

6

awk can do the job if you provide -F flag with the word which you want to use:

$ awk -F 'test'  '{print $1;print $2}'  <<<  "onetesttwotest"                                                            
one
two

In your particular case, that would be:

$ awk -F 'ABCD' '{print $1,FS}' input.txt                                                                                
171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend  ABCD

Judging from your example, you're only trying to print stuff up to ABCD so deleting everything after that is also an option:

$ awk '{print substr($0,0,match($0,/ABCD/)+4);}' input.txt                                                               
171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD.
3

grep solution:

grep -o '^.*ABCD\.' input.txt

The regular expression will match to each line that begin ^ with any character . repeated number of times * and ends with the string ABCD. The backslash \ escapes the special meaning of the dot . at the end.

The option -o will tell the grep command to print only the matched (non-empty) parts of a matching line.

pa4080
  • 30,621
3

cut can itself perform this job. Not based on a word, but based on . delimiter.

Use :

cut -f 1 -d '.' input.txt | xargs -I "%" echo %.

Output

rooney@bond-pc:~$ cat input.txt 
171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD. The task has terminated abnormally because of a program check. 16:08:27
rooney@bond-pc:~$ 
rooney@bond-pc:~$ cut -f 1 -d '.' input.txt | xargs -I "%" echo %.
171212 16082784       6264 XXX     xxxxxxxx Transaction XXXXX abend ABCD.

xargs is used here only to append . at the end of string ABCD.

Rooney
  • 975