Wednesday, October 26, 2022

[SOLVED] Iterating through files in a folder with sed

Issue

I've a list of csv-files and would like to use a for loop to edit the content for each file. I'd like to do that with sed. I have this sed commands which works fine when testing it on one file:

sed 's/[ "-]//g'

So now I want to execute this command for each file in a folder. I've tried this but so far no luck:

for i in *.csv; do sed 's/[ "-]//g' > $i.csv; done

I would like that he would overwrite each file with the edit performed by sed. The sed commands removes all spaces, the " and the '-' character.


Solution

Small changes,

for i in *.csv
do 
    sed -i 's/[ "-]//g' "$i"
done

Changes

  • when you iterate through the for you get the filenames in $i as example one.csv, two.csv etc. You can directly use these as input to the sed command.

  • -i Is for inline changes, the sed will do the substitution and updates the file for you. No output redirection is required.

  • In the code you wrote, I guess you missed any inputs to the sed command



Answered By - nu11p01n73R
Answer Checked By - Candace Johnson (WPSolving Volunteer)