Skip to content
Advertisement

Put quotes around string before first forward slash in line by line file read

I am writing a bash script that deletes all the files whose paths are given in delete.txt. delete.txt is thousands of lines long, each line has a path that is structured like this:

JavaScript

Where there is a space in the name of the first directory.

Currently, my bash script reads each line of delete.txt, saves it to$line and deletes it.

JavaScript

However, because there is a space in the first directory name, my rm command returns:

JavaScript

What can I do in my bash script to add a quote before the first and after the second words of each line before doing the rm command?

Advertisement

Answer

The problem is with rm invocation. Just correctly quote line variable:

JavaScript

Or, even simpler, you can use xargs and this oneliner which replaces the complete script:

JavaScript

This will run rm for each line in delete.txt, properly quoted. The trick here is to use -I <placeholder> option which will make sure the command rm '<placeholder>' is executed once per line (not word), each time substituting <placeholder> with filename from current line.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement