-1

I have a file containing list of filenames, like this

file1.cfg
file2.cfg
file3.cfg

I want, using the linux terminal, to split this into n files with the given filename, each also containing the filename as a string.

For example, after transformation I want the content of file1.cfg to be

filename=file1.cfg

and in file2.cfg

filename=file2.cfg

etc.

What is the best way to accomplish this?

3 Answers 3

3

Assuming your file is called configs, you can achieve this with

for i in $(cat configs); do echo "filename=$i">$i; done
1
  • for will work for simple file names, but might have issues if there are spaces in the file names.
    – MaQleod
    Feb 20, 2014 at 21:00
4

Provided that you count awk as shell, this is simply

awk '{print "filename="$0 >$0}' file.cfg
2
  • To make this space-safe, use $0 instead of $1 - and add "filename=".
    – Karsten S.
    Feb 20, 2014 at 21:09
  • Thanks, @KarstenS.; I just altered the answer. I'm so used to using awk for field manipulation I think I just reached for $1 by default. Feb 20, 2014 at 21:10
2

Something like this should do the trick:

while read line; do echo "filename=$line" > $line; done < file

it will open the file, read it line by line, and for each line it will create a file with the name being the content of the line and then write a line to that file with the contents of the echo command (being filename=). caveat: I haven't actually tested it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .