Friday, April 29, 2022

[SOLVED] Pass a list of files to sed to delete a line in them all

Issue

I am trying to do a one liner command that would delete the first line from a bunch of files. The list of files will be generated by grep command.

grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv | tr -s "\n" " " | xargs /usr/bin/sed -i '1d'

The problem is that sed can't see the list of files to act on.I'm not able to work out what is wrong with the command. Please can someone point me to my mistake.


Solution

Line numbers in sed are counted across all input files. So the address 1 only matches once per sed invocation.

In your example, only the first file in the list will get edited.

You can complete your task with loop such as this:

grep -l 'hsv,vcv,tro,ztk' "${OUTPUT_DIR}/"*.csv |
while IFS= read -r file; do
    sed -i '1d' "$file"
done


Answered By - dan
Answer Checked By - Terry (WPSolving Volunteer)