Remove extra dot in a String by grep/awk/cut

Viewed 121

I have the following text in a file, for example, output.txt

[test.tracking_utils] INFO: Tracking subtool usage: main_test
[TEST & SPEC] INFO: Uploaded file test.zip with bucket URI test/20210804144418.zip.

How to use grep o something similar to get the value as test/20210804144418.zip?

I tried

tail output.txt | grep ". test/" | awk {print $NF}
tail output.txt | grep -m1 .test/ | rev | cut -d' ' -f1 | rev

it returns test/20210804144418.zip. with extra . do you know how to remove the extra . at the end? any suggestion?

4 Answers

With awk, you could try following once.

awk '/test\//{sub(/\.$/,"");print $(NF);exit}' Input_file

2nd solution: Using match function of awk here.

awk 'match($0,/URI test\/[0-9]+\.zip/){print substr($0,RSTART+4,RLENGTH-4);exit}' Input_file

You can remove a trailing . by piping through

sed 's/\.$//'

But this may not be necessary in this case. With GNU grep or pcregrep you can extract just the path directly:

grep -Po 'with bucket URI \K.*(?=.)'

You may use this grep:

grep -oE -m1 'test/[^[:blank:]]+\.[^.]+' file

test/20210804144418.zip

RegEx Details:

  • test/: Match test/
  • [^[:blank:]]+: Match 1+ of non-whitespace characters
  • \.: Match a dot
  • [^.]+: Match 1+ of any non-dot characters

Assumptions:

  • start of desired output/string doesn't necessarily start with test
  • all lines with the desired string contain with bucket URI
  • string of interest will always be the last field (in a space-delimited) line
  • there may be more than one line of interest

Sample input:

$ cat output.txt
[test.tracking_utils] INFO: Tracking subtool usage: main_test
[TEST & SPEC] INFO: Uploaded file test.zip with bucket URI test/20210804144418.zip.
[test.tracking_utils] INFO: Tracking subtool usage: main_test
[TEST & SPEC] INFO: Uploaded file test.zip with bucket URI other/101423412.pre.zip.

A couple awk ideas:

awk '/with bucket URI/{sub(/\.$/,"",$NF);print $NF}' output.txt
awk '/with bucket URI/{print substr($NF,1,length($NF)-1)}' output.txt

Both of these generate:

test/20210804144418.zip
other/101423412.pre.zip
Related