I have a file named solution.txt . I need to check whether such file exist in current directory. if it exist, then removing that file and replacing it with (solution.txt)

Example: in my directory: wer.txt wer1.txt wer2.txt solution1.txt solution23.txt solution32.txt

i need to remove all the files starting with 'solution' ending with txt from the directory and replace it with solution.txt.

please give the shellscript solution .


you can try & adapt to remove all solution...txt files but not solution.txt if exist :

find . -type f -name "solution[0-9]*.txt" -exec rm -f {} \; 

but you cannot have more than one file name solution.txt


Perhaps is no what your asking, but here is my answer:

First you need to find those that you're looking for: find /file/where/you're/looking/at -name solution | grep txt

Once you find them you can remove them with: rm thename23.txt thename34.txt

Or merge them with (if you want to replace them at all use only one >): cat thename23.txt >> thename34.txt

You also can use the -exec option of the find command. More info here.


You didn't define what you meant by "replace them by solution.txt", but since you want to remove the other solution files first, I guess assume that you have the replacement file somewhere, otherwise the question doesn't make much sense.

I think the simplest way to do it would be

rm solution[0-9]*.txt >/dev/null && cp /from/somewhere/solution.txt .

This tries to remove the files, and if it succeeds, copies solution.txt to your working directory. With other words: You are guaranteed to have afterwards either no solution file at all, or a single one named solution.txt.

Note that this would also wipe out a file named solution5x.txt. I don't know whether this is acceptable for you. If this is an issue, you need to match the file names using a regular expression, for instance using find ... -regex.

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.