1

I have a file that looks like this

.../proj_1/file1.txt 8 2018-03-14 07:46:01
.../proj_1/file3.txt 3 2018-03-14 07:47:01
.../proj_1/file2.txt 10 2018-03-14 07:45:01
.../file1.txt 2 2018-03-14 07:50:01

and I'd like to extract date and time which is in the 3. and 4. column and save it into a variable. (dir_path is the name of the directory and source_file is the file I described above)

variable=$(grep "$dir_path/.*" source_file | grep -v "$dir_path/.*/" | awk '/[0-9]/{print ($3 $4)}')

My desired output is

2018-03-14 07:46:00
2018-03-14 07:47:00
2018-03-14 07:45:01

But with this code, the output looks like this

2018-03-1407:46:00
2018-03-1407:47:00
2018-03-1407:45:01

How do I put the space in between the date and time? Is it even possible? If I but a space into the awk expression, the the time and date is saved in separate elements which is not what I want.

Thank you for any help!

Saeko
  • 421
  • 1
  • 4
  • 14

1 Answers1

1

How about the following?

awk '/[0-9]/{print ($3" "$4)}'

Works for me:

awk '/[0-9]/{print ($3" "$4)}' file1.txt

2018-03-14 07:46:01
2018-03-14 07:47:01
2018-03-14 07:45:01
2018-03-14 07:50:01

Useful link: StackOverflow case: AWK to print field $2 first, then field $1

Andrey
  • 11
  • 4
  • Wow, this works in the terminal but doesn't work inside the script... when I iterate through my variable, the output separates the time and date into different element of my variable – Saeko Mar 14 '18 at 11:37
  • Most likely due to quotation symbols(") try to use escape characters – Andrey Mar 14 '18 at 11:42
  • Also you can specify delimiter with -F option as stated by link below: https://stackoverflow.com/questions/15597666/awk-to-print-field-2-first-then-field-1?answertab=votes#tab-top – Andrey Mar 14 '18 at 11:44