0

I have a file which contains lines like those:

-rw-rw-rw 1 root root 6379 May 24 2016 test1.CSV 
-rw-rw-rw 1 root root 23249 May 25 2016 test2.CSV 
-rw-rw-rw 1 root root 2995 May 26 2016 test3.CSV 

and I need to keep just the CSV file names. I have to use a regex but I don't know which one.

The expected result is "test1.CSV \n test2.CSV \n test3.CSV".

lgeorget
  • 13,914

4 Answers4

2

You can use grep

grep -io '[^ ]*\.csv' filename

-i, --ignore-case Ignore case distinctions, so that characters that differ only in case match each other.

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

[^ ]*\.csv matches any character but space ending with .csv

I am assuming filename with no space

or you can use awk

awk '{print $(NF)}' filename | grep -i '\.csv'

variable $(NF) is the last field in every line

dgfjxcv
  • 697
  • 1
    you can accept it as answer, if it solves your problem, as it will help other persons in future if in case – dgfjxcv Apr 16 '19 at 10:34
1

Try this,

awk '$NF~/CSV$/ {print $NF}'  file
  • extracts the lines end with CSV and prints the last field
Siva
  • 9,077
  • thanks but i mean i have file with something like this : -rw-rw-rw 1 root root 6379 May 24 2016 test1.CSV -rw-rw-rw 1 root root 23249 May 25 2016 test2.CSV -rw-rw-rw 1 root root 2995 May 26 2016 test3.CSV and i need to keep just csv file name, i have to use a regex but i dont know which one – Ayoub Hammami Apr 16 '19 at 10:10
  • @AyoubHammami try my update – Siva Apr 16 '19 at 10:55
1

Try this: [^ ]* *$

Or simply, if relevant, gawk '{print $NF}'

fra-san
  • 10,205
  • 2
  • 22
  • 43
Eran Ben-Natan
  • 568
  • 2
  • 7
0

You can use ' awk' :

awk '{print $9}' files

It will work whenever the filename is the 9th field in the line.

jcbermu
  • 4,736
  • 18
  • 26