Andrés Parada
Andrés Parada

Reputation: 319

How to add a string at the end of each line accordingly to the name of the file for a list of files?

I want to append to each line the name of the file. I guess this can be done either in awk or sed. I tried something like this but it didn't work.

for file in *.cds; do  sed -i '/^>/ s/$/[file]/' $file ; done

Where I put [file] I want the name of the file between brackets, like [name1]. Thanks for the help.

Upvotes: 1

Views: 108

Answers (2)

karakfa
karakfa

Reputation: 67537

this should do

for file in *.cds; do sed -i 's/$/['"$file"']/' "$file"; done

appends file name in square brackets at the end of each line.

UPDATE: I don't know why people want to use white spaces in file names but as commented below, you should quote the bash variables to preserve it as a logical unit for both instances.

If you want to restrict the append only lines starting with > add it as a pattern

for file in *.cds; do sed -i '/^>/s/$/['"$file"']/' "$file"; done

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 204259

With GNU awk for inplace editing:

awk -i inplace '{print $0 "[" FILENAME "]"}' *.cds

Upvotes: 1

Related Questions