1

I have many files with the extension .com, so the files are named 001.com, 002.com, 003.com, and so on.

And I have another file called headname which contains the following information:

abc=chd
dha=djj
cjas=FILENAME.chk
dhdh=hsd

I need to put the information of the file headname inside (and at the begin of) the files 001.com, 002.com, 003.com and so on... But FILENAME needs to be the filename of the file that will receive the headname information (without the .com extension).

So the output need to be:

For the 001.com:

abc=chd
dha=djj
cjas=001.chk
dhdh=hsd

For the 002.com:

abc=chd
dha=djj
cjas=002.chk
dhdh=hsd

For the 003.com:

abc=chd
dha=djj
cjas=003.chk
dhdh=hsd

And so on...

1
  • Something like for f in <files> ; do sed "s/FILENAME/$f/g' headname > "${f}.com" ; done? Commented Jan 21, 2016 at 15:21

2 Answers 2

4
set -e

for f in *.com
do
    cat <(sed "s#^cjas=FILENAME.chk\$#cjas=${f%.com}.chk#" headname) "$f" > "$f.new"
    mv -f "$f.new" "$f"
done

Explanation:

  • for f in *.com -- this loops over all file names ending with .com.
  • sed is a program that can be used to replace text.
  • s#...#...# is the substitute command.
  • ${f%.com} is the file name without the .com suffix.
  • cat <(...) "$f" -- this merges the new head with the body of the .com file.
  • The output of cat is stored into a file named 123.com.new -- mv -f "$f.new" "$f" is used to rename 123.com.new to 123.com.
Sign up to request clarification or add additional context in comments.

1 Comment

Process substitution is an unnecessary complication here; sed ... | cat - "$f" > "$f.new"
1

Something like this should work:

head=$(<headname)        # read head file into variable
head=${head//$'\n'/\\n}  # replace literal newlines with "\n" for sed
for f in *.com; do       # loop over all *.com files
  # make a backup copy of the file (named 001.com.bak etc).
  # insert the contents of $head with FILENAME replaced by the 
  # part of the filename before ".com" at the beginning of the file      
  sed -i.bak "1i${head/FILENAME/${f%.com}}" "$f"
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.