Home > Enterprise >  Pass a list of files to sed to delete a line in them all
Pass a list of files to sed to delete a line in them all

Time:12-21

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.

CodePudding user response:

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

CodePudding user response:

This might work for you (GNU sed and grep):

grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv  | xargs sed -i '1d'

The -l ouputs the file names which are received as arguments for xargs.

The -i edits in place the file and removes the first line of each file.

N.B. The -i option in sed works at a per file level, to use line numbers for each file within a stream use the -s option.

CodePudding user response:

The only solution that worked for me is this apart from the one posted by Dan above -

for k in $(grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv | tr -s "\n" " ")
do
    /usr/bin/sed -i '1d' "${k}"
done
  • Related