Cut command with word as delimiter

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?

3

5 Answers

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.

1

sed version:

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

Source:

2

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.

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like