2

I would like to write a shell script that allows me to open a text file with a particular name and write the name of the file at the beginning of every line. So, if my file is called "test" and it has three lines:

SCORE1 567
SCORE2 434
SCORE3 789 

the script would open it and change it to this:

test SCORE1 567 
test SCORE2 434
test SCORE3 789 

Then it should save it overwriting the original file.

Ideally, the script would perform this modification to all the files in a particular folder, writing inside each one the name of that particular file in every line.

Once this process is done, I will feed these files to another script that will combine them in a single one that will be later analyzed with a spreadsheet.

Could you help me with this? I have some ideas, but I would like to read yours. I almost have not experience writing shell scripts.

1 Answer 1

1

You can use the following script,

#!/bin/bash
awk -v var="$1" '{print var" "$0 }' "$1" > /tmp/temp.txt
mv /tmp/temp.txt "$1"

Give the script execution permission, as chmod +x scriptname

Run the script as,

./scriptname test

assuming "test" is the file that you are going to modify and you are running the script from the same folder where the file "test" is located.

3
  • It works very well! Thank you! Now I need to modify it to do the same with all the files in a certain folder :)
    – iiciieii
    Feb 18, 2015 at 19:21
  • use a for loop for all file as, for i in *; do ./scriptname "$i"; done
    – sourav c.
    Feb 19, 2015 at 2:00
  • Simple & elegant... Upvoted! ;-)
    – Fabby
    Feb 19, 2015 at 11:47

You must log in to answer this question.

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