usert4jju7
usert4jju7

Reputation: 1813

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

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.

Upvotes: 0

Views: 473

Answers (3)

potong
potong

Reputation: 58578

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.

Upvotes: 1

usert4jju7
usert4jju7

Reputation: 1813

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

Upvotes: 0

dan
dan

Reputation: 5251

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

Upvotes: 1

Related Questions