how to remove lines from file that don't match regex?

前端 未结 5 1158
傲寒
傲寒 2021-01-22 04:05

I have a big file that looks like this:

7f0c41d6-f9c6-47aa-a034-d40bc629c973.csv
159890
159891
24faaed6-62ee-4175-8430-5d73b09911c8.csv
159907
5bad221f-25ef-44fa         


        
5条回答
  •  清歌不尽
    2021-01-22 04:50

    If it is the case that you do not want to have to save the names of files in another file just to remove unwanted files, then this may also be an added solution for your needs (understanding that this is an old question).

    This single line for loop using the grep "\.csv" file solution recursively so you don't need to manage multiple files names being saved here or there.

    for f in *; do if [ ! "$(echo ${f} | grep -Eo '.csv')" == ".csv" ]; then rm "${f}"; fi; done
    

    As a visual aid to show you that it works as intended (for removing all files except csv files) here is a quick and dirty screenshot showing the results using your sample output.

    And here is a slightly shorter version of the single line command:

    for f in *; do if [ ! "$(echo ${f} | grep -o '.csv')" ]; then rm "${f}"; fi; done
    

    And here is it's sample output using your sample's csv file names and some randomly generated text files.

    The purpose for using such a loop with a conditional is to guarantee you only rid yourself of the files you want gone (the non-csv files) and only in the current working directory without parsing the ls command.

    Hopefully this helps you and anyone else that is looking for a similar solution.

提交回复
热议问题