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".

  • 1
    Have you tried something yourself already? Could you just use ls instead of ls -l? – Sjoerd Apr 16 at 9:59
  • 1
    Where do you keep this string, how do you produce it, and what would you want to do with it? If you are looping over all CSV files in a directory, consider using for file in *.csv; do ...; done, for example, instead of storing the ls -l or ls output. – Kusalananda Apr 16 at 10:03
  • the file is produce by a system and i have to format it to keep just csv file names. The file contains a lot of line looking like what i have said, so i do keep csv file name ==> test1.csv \n test2.csv \n test3.csv – Ayoub Hammami Apr 16 at 10:14
  • 3
    @AyoubHammami Are there spaces etc. in the filenames? – Kusalananda Apr 16 at 11:06
  • @AyoubHammami: Does "CSV" in the file have to be transformed to "csv" in the output? (Any more changes?) – DonHolgo Apr 16 at 12:00
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

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

Try this: [^ ]* *$

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

1

Try this,

awk '$NF~/CSV$/ {print $NF}'  file
  • extracts the lines end with CSV and prints the last field
  • 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 at 10:10
  • @AyoubHammami try my update – msp9011 Apr 16 at 10:55
0

You can use ' awk' :

awk '{print $9}' files

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.